canti primo tag

This commit is contained in:
David Frassi
2026-05-16 17:24:59 +02:00
commit 0c33fc6fcf
106 changed files with 28210 additions and 0 deletions
+38
View File
@@ -0,0 +1,38 @@
import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{
path: 'home',
loadChildren: () => import('./home/home.module').then( m => m.HomePageModule)
},
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
},
{
path: 'player',
loadChildren: () => import('./pages/player/player.module').then( m => m.PlayerPageModule)
},
{
path: 'display',
loadChildren: () => import('./pages/display/display.module').then( m => m.DisplayPageModule)
},
{
path: 'settings',
loadChildren: () => import('./pages/settings/settings.module').then( m => m.SettingsPageModule)
},
{
path: 'propose-canto',
loadComponent: () => import('./pages/propose-canto/propose-canto.page').then( m => m.ProposeCantoPage)
},
];
@NgModule({
imports: [
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
],
exports: [RouterModule]
})
export class AppRoutingModule { }
+4
View File
@@ -0,0 +1,4 @@
<ion-app>
<ion-router-outlet></ion-router-outlet>
<div id="global-yt-player-container" style="position: absolute; width: 1px; height: 1px; opacity: 0; pointer-events: none; top: -100px;"></div>
</ion-app>
View File
+21
View File
@@ -0,0 +1,21 @@
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [AppComponent],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
});
+41
View File
@@ -0,0 +1,41 @@
import { Component, inject, ApplicationRef } from '@angular/core';
import { SwUpdate, VersionReadyEvent } from '@angular/service-worker';
import { filter, first } from 'rxjs/operators';
import { concat, interval } from 'rxjs';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss'],
standalone: false,
})
export class AppComponent {
private swUpdate = inject(SwUpdate);
private appRef = inject(ApplicationRef);
constructor() {
this.setupUpdates();
}
private setupUpdates() {
if (this.swUpdate.isEnabled) {
// Controlla aggiornamenti ogni 5 minuti invece di 30
const everyFiveMinutes$ = interval(5 * 60 * 1000);
everyFiveMinutes$.subscribe(() => {
console.log('Checking for PWA updates...');
this.swUpdate.checkForUpdate();
});
this.swUpdate.versionUpdates
.pipe(filter((evt): evt is VersionReadyEvent => evt.type === 'VERSION_READY'))
.subscribe(() => {
if (confirm('Una nuova versione dell\'app è disponibile. Vuoi aggiornare ora?')) {
this.swUpdate.activateUpdate().then(() => {
window.location.reload();
});
}
});
}
}
}
+31
View File
@@ -0,0 +1,31 @@
import { NgModule, isDevMode } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
import { IonicStorageModule } from '@ionic/storage-angular';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { ServiceWorkerModule } from '@angular/service-worker';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
IonicModule.forRoot(),
AppRoutingModule,
HttpClientModule,
IonicStorageModule.forRoot(),
ServiceWorkerModule.register('ngsw-worker.js', {
enabled: !isDevMode(),
// Register the ServiceWorker as soon as the application is stable
// or after 30 seconds (whichever comes first).
registrationStrategy: 'registerImmediately'
})
],
providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }],
bootstrap: [AppComponent],
})
export class AppModule {}
@@ -0,0 +1,21 @@
<ion-header class="ion-no-border">
<ion-toolbar class="bg-gradient">
<ion-title class="outfit-font">Scansiona QR</ion-title>
<ion-buttons slot="end">
<ion-button (click)="cancel()" color="secondary" class="outfit-font">Chiudi</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content class="ion-no-padding">
<div class="scanner-container">
<zxing-scanner
[formats]="allowedFormats"
(scanSuccess)="onCodeResult($event)">
</zxing-scanner>
<div class="scan-overlay">
<div class="scan-frame"></div>
<p class="scan-text">Inquadra il QR Code della tua parrocchia</p>
</div>
</div>
</ion-content>
@@ -0,0 +1,63 @@
.scanner-container {
position: relative;
width: 100%;
height: 100%;
background: black;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
zxing-scanner {
width: 100%;
height: 100%;
}
.scan-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background: rgba(0, 0, 0, 0.4);
pointer-events: none;
.scan-frame {
width: 250px;
height: 250px;
border: 2px solid white;
border-radius: 20px;
box-shadow: 0 0 0 4000px rgba(0, 0, 0, 0.5);
position: relative;
&::after {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 2px;
background: var(--ion-color-secondary);
box-shadow: 0 0 10px var(--ion-color-secondary);
animation: scan 2s linear infinite;
}
}
.scan-text {
color: white;
margin-top: 24px;
font-weight: 500;
text-align: center;
padding: 0 40px;
}
}
}
@keyframes scan {
0% { top: 0; }
100% { top: 100%; }
}
@@ -0,0 +1,28 @@
import { Component, inject } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { ZXingScannerModule } from '@zxing/ngx-scanner';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { BarcodeFormat } from '@zxing/library';
@Component({
selector: 'app-qr-scanner',
templateUrl: './qr-scanner.component.html',
styleUrls: ['./qr-scanner.component.scss'],
standalone: true,
imports: [CommonModule, IonicModule, ZXingScannerModule]
})
export class QrScannerComponent {
private modalCtrl = inject(ModalController);
public allowedFormats = [BarcodeFormat.QR_CODE];
onCodeResult(result: string) {
if (result) {
this.modalCtrl.dismiss(result);
}
}
cancel() {
this.modalCtrl.dismiss();
}
}
+16
View File
@@ -0,0 +1,16 @@
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomePage } from './home.page';
const routes: Routes = [
{
path: '',
component: HomePage,
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class HomePageRoutingModule {}
+19
View File
@@ -0,0 +1,19 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { IonicModule } from '@ionic/angular';
import { FormsModule } from '@angular/forms';
import { HomePage } from './home.page';
import { HomePageRoutingModule } from './home-routing.module';
import { DragDropModule } from '@angular/cdk/drag-drop';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
HomePageRoutingModule,
DragDropModule
],
declarations: [HomePage]
})
export class HomePageModule {}
+285
View File
@@ -0,0 +1,285 @@
<ion-header class="ion-no-border">
<ion-toolbar class="bg-gradient">
<ion-title class="outfit-font">
<div class="header-logo-wrapper">
<img src="assets/icon/favicon.png" class="header-logo">
<div class="header-text-group">
<span class="app-name">CantiCristiani</span>
<span class="version-badge">v{{ version }}</span>
</div>
</div>
</ion-title>
<ion-buttons slot="end">
<div class="offline-badge-header" *ngIf="!connectivityService.isOnline()">
<ion-icon name="cloud-offline-outline"></ion-icon>
</div>
<ion-button (click)="importPlaylist()" class="add-btn">
<ion-icon slot="icon-only" name="qr-code-outline"></ion-icon>
</ion-button>
<ion-button routerLink="/propose-canto" class="add-btn" *ngIf="!playlistService.selectionMode() && settingsService.showEditor()">
<ion-icon slot="icon-only" name="add-outline"></ion-icon>
</ion-button>
<ion-button routerLink="/settings" class="settings-btn">
<ion-icon slot="icon-only" name="settings-outline"></ion-icon>
</ion-button>
</ion-buttons>
</ion-toolbar>
<ion-toolbar class="bg-gradient" *ngIf="!playlistService.selectionMode() || isAddingSongs()">
<div class="search-wrapper-group">
<div class="search-row">
<div class="search-wrapper glass">
<ion-searchbar
placeholder="Cerca un canto..."
[value]="searchQuery()"
(ionInput)="onSearch($event)"
class="custom-searchbar">
</ion-searchbar>
<ion-button fill="clear" (click)="toggleVoiceSearch()" class="voice-search-btn">
<ion-icon slot="icon-only" [name]="audioEngine.isSearching() ? 'mic' : 'mic-outline'" [color]="audioEngine.isSearching() ? 'danger' : 'secondary'"></ion-icon>
</ion-button>
</div>
</div>
<div class="filter-actions-row">
<div class="song-count-card outfit-font">
{{ filteredCanti().length }}
</div>
<div class="filter-buttons">
<ion-button
*ngIf="settingsService.showEditor()"
[fill]="showOnlyMine() ? 'solid' : 'outline'"
size="small"
(click)="toggleOnlyMine()"
color="secondary"
class="filter-chip">
Miei
<span class="close-icon-wrapper" *ngIf="showOnlyMine()" (click)="clearOnlyMine($event)">
<ion-icon slot="end" name="close-circle"></ion-icon>
</span>
</ion-button>
<ion-button
[fill]="activeFilterType() === 'liturgico' || selectedLiturgico() !== null ? 'solid' : 'outline'"
size="small"
(click)="toggleFilterType('liturgico')"
class="filter-chip">
{{ selectedLiturgico() !== null ? getSelectedLiturgicoLabel() : 'Liturgia' }}
<ion-icon slot="end" name="chevron-down-outline" *ngIf="selectedLiturgico() === null"></ion-icon>
<span class="close-icon-wrapper" *ngIf="selectedLiturgico() !== null" (click)="clearLiturgico($event)">
<ion-icon slot="end" name="close-circle"></ion-icon>
</span>
</ion-button>
<ion-button
[fill]="activeFilterType() === 'tematico' || selectedTematico() !== null ? 'solid' : 'outline'"
size="small"
(click)="toggleFilterType('tematico')"
class="filter-chip">
{{ selectedTematico() !== null ? getSelectedTematicoLabel() : 'Periodo' }}
<ion-icon slot="end" name="chevron-down-outline" *ngIf="selectedTematico() === null"></ion-icon>
<span class="close-icon-wrapper" *ngIf="selectedTematico() !== null" (click)="clearTematico($event)">
<ion-icon slot="end" name="close-circle"></ion-icon>
</span>
</ion-button>
<ion-button
[fill]="activeFilterType() === 'playlist' || playlistService.activeListName() !== null ? 'solid' : 'outline'"
size="small"
(click)="playlistService.playlists().length > 0 ? toggleFilterType('playlist') : playlistService.toggleSelectionMode()"
class="filter-chip">
{{ playlistService.activeListName() !== null ? playlistService.activeListName() : 'Playlist' }}
<ion-icon slot="end" name="chevron-down-outline" *ngIf="playlistService.activeListName() === null && playlistService.playlists().length > 0"></ion-icon>
<ion-icon slot="end" name="add-circle-outline" *ngIf="playlistService.activeListName() === null && playlistService.playlists().length === 0"></ion-icon>
<span class="close-icon-wrapper" *ngIf="playlistService.activeListName() !== null" (click)="clearSpecialList($event)">
<ion-icon slot="end" name="close-circle"></ion-icon>
</span>
</ion-button>
</div>
</div>
</div>
</ion-toolbar>
<!-- Category Scroll (Dropdown style) -->
<ion-toolbar class="bg-gradient momentos-toolbar" *ngIf="activeFilterType() || playlistService.selectionMode() || (playlistService.activeListName() && !playlistService.selectionMode())">
<div class="momento-scroll">
<!-- Selection Mode Actions -->
<div class="selection-pill glass" *ngIf="playlistService.selectionMode()">
<span class="selection-count">{{ playlistService.selectedIds().size }}</span>
<ion-button fill="clear" color="secondary" (click)="finishSelection()" [disabled]="playlistService.selectedIds().size === 0" class="mini-action-btn">
<ion-icon slot="icon-only" name="save-outline"></ion-icon>
</ion-button>
<ion-button fill="clear" color="danger" (click)="cancelSelection()" class="mini-action-btn">
<ion-icon slot="icon-only" name="close-circle-outline"></ion-icon>
</ion-button>
</div>
<!-- Active Playlist Actions -->
<div class="selection-pill glass" *ngIf="playlistService.activeListName() && !playlistService.selectionMode()">
<ion-button fill="clear" color="secondary" (click)="editPlaylist()" class="mini-action-btn">
<ion-icon slot="icon-only" name="create-outline"></ion-icon>
</ion-button>
<ion-button fill="clear" color="secondary" (click)="shareActivePlaylist()" class="mini-action-btn">
<ion-icon slot="icon-only" name="share-social-outline"></ion-icon>
</ion-button>
<ion-button fill="clear" color="danger" (click)="deleteActivePlaylist()" class="mini-action-btn" *ngIf="playlistService.activePlaylistId()">
<ion-icon slot="icon-only" name="trash-outline"></ion-icon>
</ion-button>
</div>
<!-- Filter chips -->
<div
*ngFor="let item of (activeFilterType() === 'playlist' ? playlistService.playlists() : (activeFilterType() === 'liturgico' ? cantiService.indiceLiturgico() : (activeFilterType() === 'tematico' ? cantiService.indiceTematico() : [])))"
class="momento-chip glass"
[class.active]="activeFilterType() === 'playlist' ? playlistService.activePlaylistId() === item.id : isIndexSelected(item.id)"
(click)="activeFilterType() === 'playlist' ? selectPlaylist(item) : toggleIndex(item.id, activeFilterType()!)">
{{ activeFilterType() === 'playlist' ? item.name : item.tag_name }}
</div>
</div>
</ion-toolbar>
</ion-header>
<ion-content class="bg-gradient"
(touchstart)="onTouchStart($event); onInteraction()"
(touchmove)="onTouchMove($event)"
(touchend)="onTouchEnd()"
(click)="onInteraction()">
<div class="ion-padding no-padding-top">
<div *ngIf="cantiService.loading() && filteredCanti().length === 0" class="ion-text-center ion-padding loading-container">
<div class="loading-wrapper">
<ion-spinner name="crescent" color="secondary"></ion-spinner>
<div class="percentage-label outfit-font">{{ cantiService.progress() }}%</div>
<p class="ion-margin-top" style="color: var(--ion-color-secondary)">Caricamento canti...</p>
</div>
</div>
<!-- Wrap in DragDrop only in Reorder mode -->
<div cdkDropList
[cdkDropListDisabled]="!playlistService.selectionMode() || isAddingSongs()"
(cdkDropListDropped)="drop($event)"
class="transparent-list">
<ion-item *ngFor="let canto of visibleCanti()"
[id]="'canto-' + canto.id"
class="glass ion-margin-bottom custom-item"
[class.is-playing]="youtubePlayerService.currentCantoId() === canto.id"
cdkDrag
[cdkDragDisabled]="!playlistService.selectionMode() || isAddingSongs()">
<!-- Drag Handle (visible only in reorder mode) -->
<div class="drag-handle" cdkDragHandle *ngIf="playlistService.selectionMode() && !isAddingSongs()">
<ion-icon name="reorder-two-outline"></ion-icon>
</div>
<div class="item-wrapper">
<!-- Selection Area -->
<div class="selection-column" (click)="playlistService.toggleSongSelection(canto.id); $event.stopPropagation()">
<span class="canto-number" [class.selected-number]="playlistService.selectedIds().has(canto.id)">
{{ canto.id.startsWith('my_') ? 'M' : canto.id_canti }}
</span>
</div>
<!-- Content Area -->
<div class="content-column" (click)="goToCanto(canto.id)">
<div class="top-row">
<ion-label class="info-section">
<h2 class="outfit-font" style="font-weight: 500; color: var(--ion-color-secondary)">
{{ canto.titolo }}
</h2>
<p style="color: rgba(255,255,255,0.6); margin-bottom: 2px;">{{ canto.autore || 'Autore sconosciuto' }}</p>
</ion-label>
<!-- Video Thumbnail Section -->
<div *ngIf="canto.link_youtube && canto.link_youtube.length > 5" class="thumb-section" (click)="$event.stopPropagation()">
<div class="thumb-container compact">
<ng-container *ngIf="connectivityService.isOnline(); else offlineThumb">
<div class="thumb-wrapper" (click)="playVideo($event, canto.id)">
<img [src]="cantiService.getYoutubeThumb(canto.link_youtube)"
class="thumb-img loaded"
loading="lazy">
<div class="play-overlay youtube-overlay">
<ion-icon name="play-sharp"></ion-icon>
</div>
</div>
</ng-container>
<ng-template #offlineThumb>
<div class="thumb-wrapper">
<div class="offline-thumb">
<ion-icon name="cloud-offline-outline"></ion-icon>
</div>
</div>
</ng-template>
</div>
</div>
<!-- Delete Button (only for local songs) -->
<div *ngIf="canto.id.startsWith('my_')" class="delete-section" (click)="$event.stopPropagation()">
<ion-button fill="clear" color="danger" (click)="deleteMyCanto(canto.id, $event)">
<ion-icon slot="icon-only" name="trash-outline"></ion-icon>
</ion-button>
</div>
</div>
</div>
<!-- Player bars removed from here -->
</div>
</ion-item>
</div>
<!-- Add songs / Toggle View Button -->
<div class="ion-text-center ion-margin-top" *ngIf="playlistService.selectionMode()">
<ion-button fill="solid" color="secondary" (click)="toggleAddingSongs()" class="action-mode-btn glass">
<ion-icon slot="start" [name]="isAddingSongs() ? 'list-outline' : 'add-circle-outline'"></ion-icon>
{{ isAddingSongs() ? 'Torna alla Playlist' : 'Aggiungi altri canti' }}
</ion-button>
</div>
<div *ngIf="!cantiService.loading() && filteredCanti().length === 0" class="ion-text-center ion-padding">
<p style="color: rgba(255,255,255,0.5)">Nessun canto trovato.</p>
</div>
</div>
<ion-infinite-scroll (ionInfinite)="loadData($event)" threshold="150px" [disabled]="limit() >= filteredCanti().length || (playlistService.selectionMode() && !isAddingSongs())">
<ion-infinite-scroll-content loadingSpinner="bubbles" loadingText="Caricamento altri canti...">
</ion-infinite-scroll-content>
</ion-infinite-scroll>
</ion-content>
<ion-footer *ngIf="youtubePlayerService.currentCantoId()" class="ion-no-border">
<ion-toolbar class="global-player-toolbar glass">
<div class="player-content">
<div class="controls-row">
<ion-button fill="clear" color="secondary" (click)="playPrevPreview($event)" class="skip-btn">
<ion-icon slot="icon-only" name="play-skip-back-sharp"></ion-icon>
</ion-button>
<ion-button fill="clear" color="secondary" (click)="youtubePlayerService.isPlaying() ? stopVideo($event) : playVideo($event, youtubePlayerService.currentCantoId()!)" class="play-btn">
<ion-icon slot="icon-only" [name]="youtubePlayerService.isPlaying() ? 'pause-sharp' : 'play-sharp'"></ion-icon>
</ion-button>
<ion-range
[min]="0"
[max]="youtubePlayerService.videoDuration()"
[value]="youtubePlayerService.videoProgress()"
(ionChange)="onSeek($event)"
(ionKnobMoveStart)="onSeekStart()"
(ionKnobMoveEnd)="onSeekEnd()"
color="secondary"
class="global-range">
</ion-range>
<ion-button fill="clear" color="secondary" (click)="playNextPreview($event)" class="skip-btn">
<ion-icon slot="icon-only" name="play-skip-forward-sharp"></ion-icon>
</ion-button>
<ion-button fill="clear" color="medium" (click)="stopVideo($event)" class="close-btn">
<ion-icon slot="icon-only" name="close-circle-outline"></ion-icon>
</ion-button>
</div>
</div>
</ion-toolbar>
</ion-footer>
+750
View File
@@ -0,0 +1,750 @@
.outfit-font {
font-family: 'Outfit', sans-serif;
}
.bg-gradient {
--background: radial-gradient(circle at top left, #2d3436 0%, #121212 100%);
background: radial-gradient(circle at top left, #2d3436 0%, #121212 100%);
}
.custom-searchbar {
flex: 1 !important;
--background: transparent !important;
--color: white;
--placeholder-color: rgba(255, 255, 255, 0.4);
--icon-color: var(--ion-color-secondary);
--box-shadow: none !important;
padding: 0 !important;
margin: 0 !important;
&::part(container) {
background: transparent !important;
box-shadow: none !important;
padding: 0 !important;
}
&::part(input-container) {
background: transparent !important;
}
}
.search-wrapper-group {
display: flex;
flex-direction: column;
padding: 8px 16px 12px 16px; // Added top padding for extra clearance
gap: 12px;
}
.search-row {
width: 100%;
}
.search-wrapper {
display: flex;
align-items: center;
gap: 0;
padding: 2px 4px;
border-radius: 14px;
background: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.1);
.voice-search-btn {
--padding-start: 8px;
--padding-end: 8px;
margin: 0;
height: 44px;
ion-icon {
font-size: 1.5rem;
}
}
}
.filter-actions-row {
display: flex;
align-items: center;
width: 100%;
overflow-x: auto;
gap: 12px;
padding: 4px 0;
// Hide scrollbar but keep functionality
&::-webkit-scrollbar {
display: none;
}
-ms-overflow-style: none;
scrollbar-width: none;
.song-count-card {
display: flex;
align-items: center;
justify-content: center;
background: rgba(var(--ion-color-secondary-rgb), 0.15);
border: 1px solid rgba(var(--ion-color-secondary-rgb), 0.3);
padding: 0 12px;
border-radius: 12px;
height: 32px;
font-size: 0.85rem;
font-weight: 800;
color: var(--ion-color-secondary);
backdrop-filter: blur(10px);
flex-shrink: 0;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
.filter-buttons {
display: flex;
gap: 8px;
flex-shrink: 0;
ion-button.filter-chip {
--border-radius: 20px;
--border-width: 1px;
font-family: 'Outfit', sans-serif;
font-weight: 500;
margin: 0;
min-height: 32px;
font-size: 0.85rem;
text-transform: none;
letter-spacing: normal;
.close-icon-wrapper {
display: inline-flex;
align-items: center;
justify-content: center;
margin-left: 6px;
padding: 4px;
margin-right: -8px;
cursor: pointer;
z-index: 100;
ion-icon {
font-size: 1.2rem;
margin: 0;
pointer-events: none;
}
&:active {
opacity: 0.5;
transform: scale(0.9);
}
}
}
}
}
.transparent-list {
background: transparent !important;
padding-bottom: 120px; // Spazio per il player fisso
}
ion-item.glass {
--background: rgba(255, 255, 255, 0.05);
--border-radius: 16px;
--padding-start: 16px;
--inner-padding-end: 16px;
margin-bottom: 12px;
transition: transform 0.2s ease, background 0.2s ease;
&:active {
transform: scale(0.98);
--background: rgba(255, 255, 255, 0.1);
}
}
ion-title {
font-weight: 700;
letter-spacing: 1px;
color: var(--ion-color-secondary);
padding-inline: 0;
.add-btn, .settings-btn {
--color: var(--ion-color-secondary);
--padding-start: 8px;
--padding-end: 8px;
font-size: 1.2rem;
}
.header-logo-wrapper {
display: flex;
align-items: center;
justify-content: flex-start;
gap: 12px;
padding: 20px 0 16px 24px; // Increased padding for mobile spacing
}
.header-logo {
width: 42px;
height: 42px;
border-radius: 50%;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.4);
border: 2px solid rgba(var(--ion-color-secondary-rgb), 0.2);
}
.header-text-group {
display: flex;
flex-direction: column;
align-items: flex-start;
justify-content: center;
line-height: 1;
.app-name {
font-size: 1.4rem;
font-weight: 700;
color: var(--ion-color-secondary);
margin-bottom: 2px;
}
.version-badge {
font-size: 0.8rem;
font-weight: 500;
color: rgba(255, 255, 255, 0.4);
letter-spacing: 0.5px;
}
}
}
.settings-btn {
margin-right: 16px;
}
.special-list-banner {
--background: rgba(var(--ion-color-secondary-rgb), 0.1);
--border-style: none;
border-bottom: 1px solid rgba(var(--ion-color-secondary-rgb), 0.2);
.banner-content {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0 16px;
height: 40px;
.banner-text {
display: flex;
align-items: center;
gap: 8px;
color: var(--ion-color-secondary);
font-weight: 600;
font-size: 0.9rem;
small {
opacity: 0.6;
font-weight: 400;
font-size: 0.75rem;
}
}
ion-button {
--padding-start: 4px;
--padding-end: 4px;
margin: 0;
height: 32px;
font-size: 1.2rem;
}
}
}
.results-count {
display: flex;
align-items: center;
gap: 6px;
font-size: 0.8rem;
font-weight: 600;
color: var(--ion-color-secondary);
background: rgba(var(--ion-color-secondary-rgb), 0.1);
padding: 4px 12px;
border-radius: 20px;
margin-right: 0;
border: 1px solid rgba(var(--ion-color-secondary-rgb), 0.1);
transition: all 0.2s ease;
cursor: pointer;
&.is-filtered {
background: rgba(var(--ion-color-secondary-rgb), 0.2);
border-color: var(--ion-color-secondary);
box-shadow: 0 0 10px rgba(var(--ion-color-secondary-rgb), 0.1);
}
&:active {
transform: scale(0.95);
}
ion-icon {
font-size: 1.1rem;
margin-left: 2px;
}
.canti-label {
display: inline;
}
@media (max-width: 380px) {
.canti-label {
display: none;
}
}
}
.loading-container {
display: flex;
justify-content: center;
padding: 40px 0;
}
.loading-wrapper {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
}
.percentage-label {
font-size: 2rem;
font-weight: 700;
color: var(--ion-color-secondary);
text-shadow: 0 0 15px rgba(253, 203, 110, 0.3);
}
.no-padding-top {
padding-top: 0 !important;
}
.search-wrapper-group {
display: flex;
flex-direction: column;
padding: 0 16px 8px 16px;
gap: 8px;
}
.momentos-toolbar {
--min-height: 32px;
padding-bottom: 8px;
}
.momento-scroll {
display: flex;
overflow-x: auto;
padding: 0 16px;
gap: 10px;
scrollbar-width: none;
&::-webkit-scrollbar {
display: none;
}
}
.momento-chip {
flex: 0 0 auto;
padding: 6px 16px;
border-radius: 20px;
font-size: 0.8rem;
color: rgba(255, 255, 255, 0.6);
font-family: 'Outfit', sans-serif;
border: 1px solid rgba(255, 255, 255, 0.1);
transition: all 0.3s ease;
white-space: nowrap;
&.active {
background: var(--ion-color-secondary) !important;
color: #000;
font-weight: 600;
border-color: var(--ion-color-secondary);
}
}
// Custom Item Layout
.custom-item {
--padding-start: 16px;
--inner-padding-end: 16px;
--min-height: 70px; // Reduced height
transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
&.is-playing {
--background: rgba(var(--ion-color-secondary-rgb), 0.15) !important;
border-left: 4px solid var(--ion-color-secondary);
box-shadow: inset 0 0 20px rgba(var(--ion-color-secondary-rgb), 0.1);
transform: scale(1.02);
margin-left: 8px;
margin-right: 8px;
border-radius: 12px;
z-index: 10;
}
.playlist-name-chip {
margin-right: 8px;
max-width: 150px;
span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.close-icon {
font-size: 1.2rem;
margin-left: 4px;
opacity: 0.8;
}
}
.item-wrapper {
display: flex;
align-items: center;
width: 100%;
.selection-column {
padding: 10px 14px 10px 0;
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
z-index: 100;
position: relative;
}
.content-column {
flex: 1;
display: flex;
flex-direction: column;
padding: 10px 0;
cursor: pointer;
overflow: hidden;
.top-row {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
}
.info-section {
flex: 1;
margin: 0;
padding: 0;
}
}
.canto-number {
position: relative;
width: 32px;
height: 32px;
line-height: 28px;
text-align: center;
background: rgba(var(--ion-color-secondary-rgb), 0.1);
color: var(--ion-color-secondary);
font-size: 0.85rem;
border-radius: 8px;
font-weight: 700;
border: 2px solid var(--ion-color-secondary);
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
pointer-events: none;
&.selected-number {
background: var(--ion-color-secondary) !important;
color: #000 !important;
box-shadow: 0 0 15px rgba(var(--ion-color-secondary-rgb), 0.5);
transform: scale(1.1);
}
}
}
.player-inline-row {
width: 100%;
display: flex;
align-items: center;
gap: 4px;
&.full-width {
margin-top: 4px;
padding-top: 4px;
border-top: 1px solid rgba(255, 255, 255, 0.05);
}
ion-range {
flex: 1;
padding: 0;
--bar-height: 2px;
--knob-size: 10px;
}
}
.thumb-container {
&.compact {
width: 50px;
height: 38px;
border-radius: 8px;
margin-left: 12px;
}
}
.thumb-wrapper {
width: 100%;
height: 100%;
position: relative;
cursor: pointer;
}
.hidden-player {
position: absolute;
width: 1px;
height: 1px;
opacity: 0;
pointer-events: none;
}
.thumb-img {
width: 100%;
height: 100%;
object-fit: cover;
opacity: 0;
transition: opacity 0.5s ease;
&.loaded {
opacity: 1;
}
}
.skeleton {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: linear-gradient(
90deg,
rgba(255, 255, 255, 0.05) 25%,
rgba(255, 255, 255, 0.1) 50%,
rgba(255, 255, 255, 0.05) 75%
);
background-size: 200% 100%;
animation: shimmer 1.5s infinite;
}
.play-overlay {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: rgba(0, 0, 0, 0.5);
border-radius: 50%;
width: 24px;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
color: white;
backdrop-filter: blur(4px);
z-index: 2;
pointer-events: none;
ion-icon {
font-size: 14px;
margin-left: 2px;
}
}
.youtube-overlay {
background: rgba(0, 0, 0, 0.6) !important;
ion-icon {
color: #ff0000;
font-size: 16px;
margin-left: 0;
}
}
.offline-thumb {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background: rgba(255, 255, 255, 0.05);
color: rgba(255, 255, 255, 0.3);
gap: 4px;
ion-icon {
font-size: 1.2rem;
}
span {
font-size: 0.6rem;
text-transform: uppercase;
font-weight: 700;
font-family: 'Outfit', sans-serif;
}
}
}
@keyframes shimmer {
0% {
background-position: 200% 0;
}
100% {
background-position: -200% 0;
}
}
.finish-selection-fab {
--border-radius: 30px;
width: auto;
min-width: 120px;
.fab-content {
display: flex;
align-items: center;
padding: 0 16px;
gap: 8px;
ion-icon {
font-size: 1.4rem;
}
.fab-label {
font-size: 0.9rem;
font-weight: 600;
text-transform: none;
}
}
}
.selection-pill {
display: flex;
align-items: center;
gap: 4px;
background: rgba(var(--ion-color-secondary-rgb), 0.15) !important;
border: 1px solid rgba(var(--ion-color-secondary-rgb), 0.3);
padding: 2px 4px 2px 10px;
border-radius: 20px;
height: 32px;
flex-shrink: 0;
.selection-count {
font-size: 0.9rem;
font-weight: 800;
color: var(--ion-color-secondary);
margin-right: 4px;
}
.mini-action-btn {
--padding-start: 4px;
--padding-end: 4px;
margin: 0;
height: 28px;
min-width: 32px;
ion-icon {
font-size: 1.2rem;
}
}
}
.small-action-btn {
--padding-start: 4px;
--padding-end: 4px;
height: 32px;
margin: 0;
ion-icon {
font-size: 1.3rem !important;
}
}
.drag-handle {
display: flex;
align-items: center;
justify-content: center;
padding: 0 12px 0 0;
cursor: grab;
color: rgba(255, 255, 255, 0.3);
ion-icon {
font-size: 1.8rem;
}
&:active {
cursor: grabbing;
}
}
.action-mode-btn {
--border-radius: 20px;
--box-shadow: 0 4px 15px rgba(0,0,0,0.3);
font-weight: 700;
letter-spacing: 0.5px;
height: 44px;
}
@media (max-width: 360px) {
.header-logo-wrapper {
margin-bottom: 12px !important;
}
}
/* GLOBAL PLAYER FOOTER */
.global-player-toolbar {
--background: transparent;
--padding-top: 4px;
--padding-bottom: 4px;
--padding-start: 12px;
--padding-end: 12px;
&.glass {
background: rgba(26, 26, 46, 0.95) !important;
backdrop-filter: blur(20px);
border-top: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 0 !important;
box-shadow: none !important;
}
.player-content {
display: flex;
flex-direction: column;
padding: 0;
}
.controls-row {
display: flex;
align-items: center;
gap: 4px;
.play-btn {
--padding-start: 0;
--padding-end: 0;
height: 44px;
width: 44px;
ion-icon {
font-size: 2.2rem;
}
}
.skip-btn, .close-btn {
--padding-start: 0;
--padding-end: 0;
height: 36px;
width: 36px;
ion-icon {
font-size: 1.4rem;
}
}
.global-range {
flex: 1;
--bar-height: 4px;
--knob-size: 14px;
padding-top: 0;
padding-bottom: 0;
}
}
}
/* Adjust bottom spacing for list when player is active */
.transparent-list {
padding-bottom: 100px !important;
}
+24
View File
@@ -0,0 +1,24 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { IonicModule } from '@ionic/angular';
import { HomePage } from './home.page';
describe('HomePage', () => {
let component: HomePage;
let fixture: ComponentFixture<HomePage>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [HomePage],
imports: [IonicModule.forRoot()]
}).compileComponents();
fixture = TestBed.createComponent(HomePage);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
+762
View File
@@ -0,0 +1,762 @@
import { Component, computed, signal, inject, effect, OnDestroy } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { CantiService } from '../services/canti.service';
import { Router, ActivatedRoute } from '@angular/router';
import { AudioEngineService } from '../services/audio-engine.service';
import { ThemeService } from '../services/theme.service';
import { ConnectivityService } from '../services/connectivity.service';
import { PlaylistService } from '../services/playlist.service';
import { SettingsService } from '../services/settings.service';
import { VERSION } from '../version';
import { YoutubePlayerService } from '../services/youtube-player.service';
import { ModalController, AlertController, ToastController } from '@ionic/angular';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { MyCantiService } from '../services/my-canti.service';
import { QrScannerComponent } from '../components/qr-scanner/qr-scanner.component';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
standalone: false,
})
export class HomePage implements OnDestroy {
public searchQuery = signal<string>('');
public selectedLiturgico = signal<number | null>(null);
public selectedTematico = signal<number | null>(null);
public showOnlyMine = signal<boolean>(false);
public activeFilterType = signal<'liturgico' | 'tematico' | 'playlist' | null>(null);
public loadedThumbs = new Set<string>();
public version = VERSION;
public isAddingSongs = signal<boolean>(false);
public reorderList = signal<any[]>([]);
public limit = signal<number>(30);
public fontSize = signal<number>(1.0);
public youtubePlayerService = inject(YoutubePlayerService);
public isSeeking = false;
private readonly MIN_FONT = 0.6;
private readonly MAX_FONT = 5.0;
private initialPinchDistance: number | null = null;
private initialFontSize: number = 1.0;
private sanitizer = inject(DomSanitizer);
public audioEngine = inject(AudioEngineService);
public themeService = inject(ThemeService);
public connectivityService = inject(ConnectivityService);
public cantiService = inject(CantiService);
public myCantiService = inject(MyCantiService);
public playlistService = inject(PlaylistService);
public settingsService = inject(SettingsService);
private router = inject(Router);
private route = inject(ActivatedRoute);
private modalCtrl = inject(ModalController);
private alertCtrl = inject(AlertController);
private toastCtrl = inject(ToastController);
private firstInteraction = true;
onInteraction() {
if (this.firstInteraction) {
this.firstInteraction = false;
}
}
private scrollEffect = effect(() => {
const activeId = this.youtubePlayerService.currentCantoId();
if (activeId) {
// Delay slightly to ensure DOM is updated and classes are applied
setTimeout(() => {
const element = document.getElementById('canto-' + activeId);
if (element) {
element.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}, 500);
}
});
private normalize(str: string | undefined): string {
if (!str) return '';
return str
.toLowerCase()
.replace(/['‘’´`]/g, "'")
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/hallelujah/g, 'alleluia')
.replace(/halleluja/g, 'alleluia')
.replace(/alleluja/g, 'alleluia');
}
public filteredCanti = computed(() => {
const query = this.normalize(this.searchQuery());
const litId = this.selectedLiturgico();
const temId = this.selectedTematico();
const onlyMine = this.showOnlyMine();
let list = [...this.cantiService.canti(), ...this.myCantiService.myCanti()];
if (onlyMine) {
list = this.myCantiService.myCanti();
}
if (litId !== null) {
list = list.filter(c => c.id_momenti?.includes(litId));
}
if (temId !== null) {
list = list.filter(c => c.id_momenti?.includes(temId));
}
// Special List handling (from QR Code or Saved Playlists)
const activeIds = this.playlistService.activeListIds();
const selectionMode = this.playlistService.selectionMode();
// If we are in selection mode, only show restricted list if NOT adding songs AND we have a base list to reorder
if (selectionMode && !this.isAddingSongs() && activeIds.length > 0) {
return this.reorderList();
}
// If we have an active playlist and NOT in selection mode, show ONLY those songs
if (activeIds.length > 0 && !selectionMode) {
// Filter only songs in the special list and KEEP THE ORDER
return activeIds
.map(id => list.find(c => c.id === id))
.filter((c): c is any => !!c);
}
if (!query) return list;
// Converte "uno" in "1" per facilitare la ricerca vocale (es. "numero uno")
const processedQuery = query.replace(/\buno\b/g, '1');
// Se la ricerca inizia con "numero" o "nr", filtra esattamente per id_canti
const numberMatchPattern = processedQuery.match(/^(?:numero|nr\.?)\s*(\d+)$/);
if (numberMatchPattern) {
const targetId = numberMatchPattern[1];
return list.filter(c => c.id_canti.toString() === targetId);
}
return list.filter(c => {
const titleMatch = this.normalize(c.titolo).includes(query);
const authorMatch = this.normalize(c.autore).includes(query);
const numberMatch = c.id_canti.toString().includes(query);
// Strip tags like {Chorus} and newlines from lyrics before searching
const lyricsPlain = (c.testo || '')
.replace(/{.*?}/g, '')
.replace(/\n/g, ' ');
const lyricsMatch = this.normalize(lyricsPlain).includes(query);
return titleMatch || authorMatch || lyricsMatch || numberMatch;
});
});
public visibleCanti = computed(() => {
return this.filteredCanti().slice(0, this.limit());
});
constructor() {
// Sync speech recognition results to search query
effect(() => {
const transcript = this.audioEngine.searchTranscript();
if (transcript) {
this.searchQuery.set(transcript);
}
});
this.route.queryParams.subscribe(params => {
if (params['import']) {
this.handleImport(params['import']);
}
});
effect(() => {
const selectionMode = this.playlistService.selectionMode();
const selectedIds = this.playlistService.selectedIds();
const activeIds = this.playlistService.activeListIds();
if (selectionMode) {
if (activeIds.length === 0 && !this.isAddingSongs()) {
this.isAddingSongs.set(true);
}
const currentIds = this.reorderList().map(c => c.id);
const newIds = Array.from(selectedIds);
// Use a set of IDs for faster lookup
const currentIdSet = new Set(currentIds);
const newIdSet = new Set(newIds);
// Check if there are differences in the SET of IDs
const added = newIds.filter(id => !currentIdSet.has(id));
const removed = currentIds.filter(id => !newIdSet.has(id));
if (added.length > 0 || removed.length > 0) {
let updatedList = [...this.reorderList()];
// Remove songs no longer selected
if (removed.length > 0) {
updatedList = updatedList.filter(c => newIdSet.has(c.id));
}
// Add newly selected songs at the end
if (added.length > 0) {
const newSongs = added.map(id => this.findCanto(id)).filter((c): c is any => !!c);
updatedList = [...updatedList, ...newSongs];
}
this.reorderList.set(updatedList);
}
} else {
this.isAddingSongs.set(false);
}
}, { allowSignalWrites: true });
}
handleImport(base64: string) {
try {
const decoded = decodeURIComponent(escape(atob(base64)));
const json = JSON.parse(decoded);
if (this.playlistService.processImportJson(json)) {
this.router.navigate([], { queryParams: { import: null }, queryParamsHandling: 'merge' });
}
} catch (e) {
console.error('Failed to import playlist', e);
}
}
ionViewWillLeave() {
}
ngOnDestroy() {
this.audioEngine.stopSearchRecognition();
}
onSearch(event: any) {
this.searchQuery.set(event.detail.value);
this.limit.set(30);
}
async deleteMyCanto(id: string, event: Event) {
event.stopPropagation();
const alert = await this.alertCtrl.create({
header: 'Elimina Canto',
message: 'Sei sicuro di voler eliminare questo canto dai tuoi brani personali?',
buttons: [
{ text: 'Annulla', role: 'cancel' },
{
text: 'Elimina',
role: 'destructive',
handler: () => {
this.myCantiService.deleteCanto(id);
}
}
]
});
await alert.present();
}
findCanto(id: string) {
return [...this.cantiService.canti(), ...this.myCantiService.myCanti()].find(c => c.id === id);
}
getPlayingCanto() {
const id = this.youtubePlayerService.currentCantoId();
if (!id) return null;
return this.findCanto(id);
}
goToCanto(id: string) {
if (this.playlistService.selectionMode()) {
this.playlistService.toggleSongSelection(id);
return;
}
const params: any = { id };
const isPlaying = this.youtubePlayerService.isPlaying();
if (this.youtubePlayerService.currentCantoId() === id && isPlaying) {
params.t = Math.floor(this.youtubePlayerService.videoProgress());
}
this.playlistService.autoPlayPlaylist.set(isPlaying);
this.router.navigate(['/player'], { queryParams: params });
}
toggleOnlyMine() {
this.showOnlyMine.update(v => !v);
if (this.showOnlyMine()) {
this.selectedLiturgico.set(null);
this.selectedTematico.set(null);
}
this.limit.set(10);
}
clearOnlyMine(event: Event) {
event.stopPropagation();
this.showOnlyMine.set(false);
this.limit.set(10);
}
toggleIndex(id: number, type: 'liturgico' | 'tematico' | 'playlist') {
if (type === 'liturgico') {
this.selectedLiturgico.update(cur => cur === id ? null : id);
} else if (type === 'tematico') {
this.selectedTematico.update(cur => cur === id ? null : id);
}
this.showOnlyMine.set(false);
this.activeFilterType.set(null);
this.limit.set(10);
}
clearLiturgico(event: Event) {
event.stopPropagation();
this.selectedLiturgico.set(null);
this.activeFilterType.set(null);
this.limit.set(10);
}
clearTematico(event: Event) {
event.stopPropagation();
this.selectedTematico.set(null);
this.activeFilterType.set(null);
this.limit.set(10);
}
isIndexSelected(id: number): boolean {
return this.selectedLiturgico() === id || this.selectedTematico() === id;
}
clearFilters() {
const type = this.activeFilterType();
if (this.playlistService.activeListIds().length > 0) {
this.clearSpecialList();
}
if (type === 'liturgico') {
if (this.selectedLiturgico() === null) {
this.selectedTematico.set(null);
} else {
this.selectedLiturgico.set(null);
}
} else if (type === 'tematico') {
if (this.selectedTematico() === null) {
this.selectedLiturgico.set(null);
} else {
this.selectedTematico.set(null);
}
} else {
this.selectedLiturgico.set(null);
this.selectedTematico.set(null);
}
this.showOnlyMine.set(false);
this.searchQuery.set('');
this.audioEngine.clearSearchTranscript();
}
activeFiltersCount(): number {
let count = 0;
if (this.selectedLiturgico() !== null) count++;
if (this.selectedTematico() !== null) count++;
return count;
}
getSelectedLiturgicoLabel(): string | null {
const id = this.selectedLiturgico();
if (id === null) return null;
return this.cantiService.indiceLiturgico().find(m => m.id === id)?.tag_name || null;
}
getSelectedTematicoLabel(): string | null {
const id = this.selectedTematico();
if (id === null) return null;
return this.cantiService.indiceTematico().find(m => m.id === id)?.tag_name || null;
}
hasActiveFilters(): boolean {
return this.selectedLiturgico() !== null ||
this.selectedTematico() !== null ||
this.showOnlyMine() ||
this.playlistService.activeListName() !== null ||
this.searchQuery() !== '';
}
clearAllFilters() {
this.selectedLiturgico.set(null);
this.selectedTematico.set(null);
this.showOnlyMine.set(false);
this.playlistService.activeListIds.set([]);
this.playlistService.activeListName.set(null);
this.playlistService.activePlaylistId.set(null);
this.searchQuery.set('');
this.activeFilterType.set(null);
this.limit.set(10);
}
toggleFilterType(type: 'liturgico' | 'tematico' | 'playlist') {
if (this.activeFilterType() === type) {
this.activeFilterType.set(null);
} else {
this.activeFilterType.set(type);
}
}
selectPlaylist(pl: any) {
this.playlistService.activeListIds.set(pl.ids);
this.playlistService.activeListName.set(pl.name);
this.playlistService.activePlaylistId.set(pl.id);
this.activeFilterType.set(null);
this.limit.set(50);
// Clear other filters
this.selectedLiturgico.set(null);
this.selectedTematico.set(null);
this.showOnlyMine.set(false);
}
onImgLoad(id: string) {
this.loadedThumbs.add(id);
}
openYoutube(event: Event, link: string) {
event.stopPropagation();
const videoId = this.cantiService.getYoutubeId(link);
if (videoId) {
window.open(`https://www.youtube.com/watch?v=${videoId}`, '_blank');
}
}
playVideo(event: Event, id: string) {
event.stopPropagation();
this.youtubePlayerService.setMediaSessionCallbacks(
() => this.playNextPreview(),
() => this.playPrevPreview()
);
this.youtubePlayerService.initPlayer(
id,
0,
() => {
if (this.settingsService.autoAdvance()) {
this.playNextPreview();
} else {
this.youtubePlayerService.stop();
}
},
() => {
if (this.settingsService.autoAdvance()) {
setTimeout(() => this.playNextPreview(), 500);
} else {
this.youtubePlayerService.stop();
}
}
);
}
stopVideo(event: Event) {
if (event) event.stopPropagation();
this.youtubePlayerService.stop();
this.playlistService.autoPlayPlaylist.set(false);
}
playNextPreview(event?: Event) {
if (event) event.stopPropagation();
const currentId = this.youtubePlayerService.currentCantoId();
if (!currentId) return;
const list = this.visibleCanti();
const currentIndex = list.findIndex(c => c.id === currentId);
for (let i = currentIndex + 1; i < list.length; i++) {
if (list[i].link_youtube) {
this.playVideo(new Event('skip'), list[i].id);
setTimeout(() => {
const el = document.getElementById('canto-' + list[i].id);
if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' });
}, 300);
return;
}
}
this.youtubePlayerService.stop();
}
playPrevPreview(event?: Event) {
if (event) event.stopPropagation();
const currentId = this.youtubePlayerService.currentCantoId();
if (!currentId) return;
const list = this.visibleCanti();
const currentIndex = list.findIndex(c => c.id === currentId);
for (let i = currentIndex - 1; i >= 0; i--) {
if (list[i].link_youtube) {
this.playVideo(new Event('skip'), list[i].id);
setTimeout(() => {
const el = document.getElementById('canto-' + list[i].id);
if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' });
}, 300);
return;
}
}
}
onSeek(event: any) {
this.youtubePlayerService.seekTo(event.detail.value);
}
onSeekStart() {
this.isSeeking = true;
}
onSeekEnd() {
this.isSeeking = false;
}
getMomentiForCanto(ids: number[] | undefined): any[] {
if (!ids) return [];
return this.cantiService.momenti()
.filter(m => ids.includes(m.id));
}
filterByMomento(event: Event, id: number) {
event.stopPropagation();
// Use liturgico as default for momento tags
this.toggleIndex(id, 'liturgico');
// Scroll to top to show results
const content = document.querySelector('ion-content');
if (content) (content as any).scrollToTop(300);
}
loadData(event: any) {
setTimeout(() => {
this.limit.update(l => l + 10);
event.target.complete();
if (this.limit() >= this.filteredCanti().length) {
event.target.disabled = true;
}
}, 500);
}
// --- Touch Gestures for Pinch-to-Zoom ---
onTouchStart(event: TouchEvent) {
if (event.touches.length === 2) {
this.initialPinchDistance = this.getDistance(event.touches[0], event.touches[1]);
this.initialFontSize = this.fontSize();
}
}
onTouchMove(event: TouchEvent) {
if (event.touches.length === 2 && this.initialPinchDistance !== null) {
// We don't preventDefault here to allow scrolling if needed,
// but usually pinch should be captured.
const currentDistance = this.getDistance(event.touches[0], event.touches[1]);
const ratio = currentDistance / this.initialPinchDistance;
let newSize = this.initialFontSize * ratio;
// Clamp values
newSize = Math.max(this.MIN_FONT, Math.min(this.MAX_FONT, newSize));
if (Math.abs(newSize - this.fontSize()) > 0.01) {
this.fontSize.set(newSize);
}
}
}
onTouchEnd() {
this.initialPinchDistance = null;
}
private getDistance(t1: Touch, t2: Touch): number {
return Math.sqrt(Math.pow(t1.clientX - t2.clientX, 2) + Math.pow(t1.clientY - t2.clientY, 2));
}
handleScannedData(data: string) {
if (!data) return;
if (data.includes('?import=')) {
try {
const base64 = data.split('?import=')[1];
this.handleImport(base64);
} catch (e) {
console.error('Failed to parse scanned link', e);
}
} else if (data.startsWith('canti:')) {
const parts = data.replace('canti:', '').split(':');
let idsStr = '';
if (parts.length > 1) {
this.playlistService.activeListName.set(parts[0]);
idsStr = parts[1];
} else {
this.playlistService.activeListName.set('Lista Parrocchiale');
idsStr = parts[0];
}
const ids = idsStr.split(',').map(id => id.trim());
this.playlistService.activeListIds.set(ids);
this.limit.set(50); // Show more initially for special lists
// Clear other filters to avoid confusion
this.selectedLiturgico.set(null);
this.selectedTematico.set(null);
}
}
toggleVoiceSearch() {
if (this.audioEngine.isSearching()) {
this.audioEngine.stopSearchRecognition();
} else {
this.audioEngine.startSearchRecognition();
}
}
async finishSelection() {
const alert = await this.alertCtrl.create({
header: 'Salva Playlist',
inputs: [
{
name: 'name',
type: 'text',
placeholder: 'Nome della playlist',
value: this.playlistService.activeListName() || ''
}
],
buttons: [
{
text: 'Annulla',
role: 'cancel'
},
{
text: 'Salva',
handler: async (data) => {
if (data.name) {
const ids = this.reorderList().map(s => s.id);
await this.playlistService.savePlaylist(data.name, ids);
const toast = await this.toastCtrl.create({
message: 'Playlist salvata!',
duration: 2000,
color: 'success'
});
await toast.present();
this.isAddingSongs.set(false);
this.playlistService.selectionMode.set(false);
this.playlistService.selectedIds.set(new Set());
return true;
}
return false;
}
}
]
});
await alert.present();
}
cancelSelection() {
const id = this.playlistService.activePlaylistId();
if (id) {
const pl = this.playlistService.playlists().find(p => p.id === id);
if (pl) {
this.playlistService.activeListIds.set(pl.ids);
this.playlistService.activeListName.set(pl.name);
}
}
this.playlistService.selectionMode.set(false);
this.playlistService.selectedIds.set(new Set());
this.isAddingSongs.set(false);
}
clearSpecialList(event?: Event) {
if (event) event.stopPropagation();
this.playlistService.activeListIds.set([]);
this.playlistService.activeListName.set(null);
this.playlistService.activePlaylistId.set(null);
this.limit.set(30);
}
playPlaylist() {
const ids = this.playlistService.activeListIds();
if (ids.length > 0) {
this.playlistService.autoPlayPlaylist.set(true);
this.router.navigate(['/player'], { queryParams: { id: ids[0] } });
}
}
shareActivePlaylist() {
const ids = this.playlistService.activeListIds();
const name = this.playlistService.activeListName() || 'Playlist';
this.playlistService.sharePlaylistQR(ids, name);
}
async importPlaylist() {
const modal = await this.modalCtrl.create({
component: QrScannerComponent
});
await modal.present();
const { data } = await modal.onWillDismiss();
if (!data) return;
this.handleScannedData(data);
}
async deleteActivePlaylist() {
const id = this.playlistService.activePlaylistId();
const name = this.playlistService.activeListName();
if (!id || !name) return;
const alert = await this.alertCtrl.create({
header: 'Elimina Playlist',
message: `Vuoi davvero eliminare "${name}"?`,
buttons: [
{ text: 'Annulla', role: 'cancel' },
{
text: 'Elimina',
role: 'destructive',
handler: () => {
this.playlistService.deletePlaylist(id);
this.clearSpecialList();
}
}
]
});
await alert.present();
}
editPlaylist() {
const ids = this.playlistService.activeListIds();
const name = this.playlistService.activeListName();
// Prova a recuperare l'ID se stiamo editando una playlist salvata
const found = this.playlistService.playlists().find(p => p.name === name);
if (found) {
this.playlistService.activePlaylistId.set(found.id);
}
this.playlistService.selectedIds.set(new Set(ids));
const songs = ids.map(id => this.findCanto(id)).filter((c): c is any => !!c);
this.reorderList.set(songs);
this.playlistService.selectionMode.set(true);
this.isAddingSongs.set(false); // Default to reorder view
// Svuota la playlist attiva per mostrare tutto l'elenco in modalità selezione
this.playlistService.activeListIds.set([]);
this.playlistService.activeListName.set(name);
}
drop(event: CdkDragDrop<any[]>) {
const arr = [...this.reorderList()];
moveItemInArray(arr, event.previousIndex, event.currentIndex);
this.reorderList.set(arr);
}
toggleAddingSongs() {
this.isAddingSongs.update(v => !v);
this.limit.set(10);
}
}
@@ -0,0 +1,17 @@
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { DisplayPage } from './display.page';
const routes: Routes = [
{
path: '',
component: DisplayPage
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class DisplayPageRoutingModule {}
+20
View File
@@ -0,0 +1,20 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { DisplayPageRoutingModule } from './display-routing.module';
import { DisplayPage } from './display.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
DisplayPageRoutingModule
],
declarations: [DisplayPage]
})
export class DisplayPageModule {}
+46
View File
@@ -0,0 +1,46 @@
<ion-content [fullscreen]="true" class="bg-gradient">
<div class="display-wrapper"
[style.fontSize.rem]="fontSize()"
(touchstart)="onTouchStart($event)"
(touchmove)="onTouchMove($event)"
(touchend)="onTouchEnd()">
<div class="lyrics-window">
<!-- Previous line -->
<div *ngIf="displayLines().prev" class="prev-line">
<ng-container *ngIf="showChords(); else prevText">
<span *ngFor="let seg of displayLines().prev!.segments" class="chord-segment">
<span *ngIf="seg.chord" class="chord">{{ seg.chord }}</span>
<span class="seg-text">{{ seg.text }}</span>
</span>
</ng-container>
<ng-template #prevText>{{ displayLines().prev!.text }}</ng-template>
</div>
<!-- Active line -->
<div *ngIf="displayLines().current" class="active-line outfit-font">
<ng-container *ngIf="showChords(); else currentText">
<span *ngFor="let seg of displayLines().current!.segments" class="chord-segment">
<span *ngIf="seg.chord" class="chord">{{ seg.chord }}</span>
<span class="seg-text">{{ seg.text }}</span>
</span>
</ng-container>
<ng-template #currentText>{{ displayLines().current!.text }}</ng-template>
</div>
<!-- Next line -->
<div *ngIf="displayLines().next" class="next-line">
<ng-container *ngIf="showChords(); else nextText">
<span *ngFor="let seg of displayLines().next!.segments" class="chord-segment">
<span *ngIf="seg.chord" class="chord">{{ seg.chord }}</span>
<span class="seg-text">{{ seg.text }}</span>
</span>
</ng-container>
<ng-template #nextText>{{ displayLines().next!.text }}</ng-template>
</div>
</div>
<div class="footer-info">
<div class="title-label outfit-font">{{ canto()?.titolo }}</div>
</div>
</div>
</ion-content>
+91
View File
@@ -0,0 +1,91 @@
.bg-gradient {
--background: radial-gradient(circle at top, #1e272e 0%, #000000 100%);
background: radial-gradient(circle at top, #1e272e 0%, #000000 100%);
}
.display-wrapper {
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding: 5% 10%;
text-align: center;
transition: font-size 0.2s ease;
touch-action: none; /* Support pinch-to-zoom */
}
.lyrics-window {
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
gap: 2rem;
width: 100%;
}
.active-line {
font-size: 5rem;
font-weight: 700;
color: var(--ion-color-secondary);
text-shadow: 0 0 20px rgba(253, 203, 110, 0.4);
line-height: 1.2;
}
.prev-line, .next-line {
font-size: 2.5rem;
color: rgba(255, 255, 255, 0.2);
font-weight: 300;
}
// ─── Chord segments for display ────────────────
.chord-segment {
display: inline-flex;
flex-direction: column;
vertical-align: bottom;
}
.chord {
color: #e74c3c;
font-weight: 700;
font-size: 0.4em;
line-height: 1.2;
min-height: 0.5em;
font-family: 'Outfit', sans-serif;
letter-spacing: 0.5px;
}
.active-line .chord {
color: #e74c3c;
font-size: 0.35em;
}
.prev-line .chord, .next-line .chord {
color: rgba(231, 76, 60, 0.4);
font-size: 0.5em;
}
.active-line, .prev-line, .next-line {
display: flex;
flex-wrap: wrap;
align-items: flex-end;
justify-content: center;
}
.seg-text {
white-space: pre-wrap;
}
.footer-info {
margin-top: 2rem;
border-top: 1px solid rgba(255, 255, 255, 0.1);
padding-top: 1rem;
width: 100%;
.title-label {
font-size: 1.5rem;
color: rgba(255, 255, 255, 0.4);
text-transform: uppercase;
letter-spacing: 2px;
}
}
@@ -0,0 +1,17 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { DisplayPage } from './display.page';
describe('DisplayPage', () => {
let component: DisplayPage;
let fixture: ComponentFixture<DisplayPage>;
beforeEach(() => {
fixture = TestBed.createComponent(DisplayPage);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
+123
View File
@@ -0,0 +1,123 @@
import { Component, OnInit, OnDestroy, signal, computed, inject } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { CantiService, Canto } from '../../services/canti.service';
import { LyricsParserService, ParsedSection } from '../../services/lyrics-parser.service';
@Component({
selector: 'app-display',
templateUrl: './display.page.html',
styleUrls: ['./display.page.scss'],
standalone: false
})
export class DisplayPage implements OnInit, OnDestroy {
public canto = signal<Canto | null>(null);
public showChords = signal<boolean>(false);
public fontSize = signal<number>(1.0);
public currentLineIndex = signal<number>(0);
public parsedSections = computed<ParsedSection[]>(() => {
const c = this.canto();
if (!c) return [];
if (this.showChords() && c.accordi) {
return this.lyricsParser.parseAccordi(c.accordi);
}
return this.lyricsParser.parseText(c.testo);
});
/** Get the current line text and surrounding lines from flat index */
public displayLines = computed(() => {
const sections = this.parsedSections();
const idx = this.currentLineIndex();
const allLines: { text: string; segments: any[]; sectionType: string }[] = [];
for (const section of sections) {
for (const line of section.lines) {
allLines.push({ text: line.text, segments: line.segments, sectionType: section.type });
}
}
return {
prev: idx > 0 ? allLines[idx - 1] : null,
current: allLines[idx] || null,
next: idx < allLines.length - 1 ? allLines[idx + 1] : null
};
});
private channel = new BroadcastChannel('karaoke_sync');
private readonly MIN_FONT = 0.6;
private readonly MAX_FONT = 5.0;
private initialPinchDistance: number | null = null;
private initialFontSize: number = 1.0;
private route = inject(ActivatedRoute);
private cantiService = inject(CantiService);
private lyricsParser = inject(LyricsParserService);
constructor() { }
ngOnInit() {
this.route.queryParams.subscribe(params => {
const id = params['id'];
if (id) {
const found = this.cantiService.getCantoById(id);
if (found) this.canto.set(found);
}
});
this.channel.onmessage = (event) => {
if (event.data.type === 'SYNC_INDEX') {
this.currentLineIndex.set(event.data.index);
}
if (event.data.type === 'SYNC_CANTO') {
const found = this.cantiService.getCantoById(event.data.id);
if (found) this.canto.set(found);
}
if (event.data.type === 'SYNC_CHORDS') {
this.showChords.set(event.data.showChords);
}
if (event.data.type === 'SYNC_FONT') {
this.fontSize.set(event.data.fontSize);
}
};
}
ngOnDestroy() {
this.channel.close();
}
// --- Touch Gestures for Pinch-to-Zoom ---
onTouchStart(event: TouchEvent) {
if (event.touches.length === 2) {
this.initialPinchDistance = this.getDistance(event.touches[0], event.touches[1]);
this.initialFontSize = this.fontSize();
}
}
onTouchMove(event: TouchEvent) {
if (event.touches.length === 2 && this.initialPinchDistance !== null) {
event.preventDefault(); // Prevent browser zoom/scroll
const currentDistance = this.getDistance(event.touches[0], event.touches[1]);
const ratio = currentDistance / this.initialPinchDistance;
let newSize = this.initialFontSize * ratio;
// Clamp values
newSize = Math.max(this.MIN_FONT, Math.min(this.MAX_FONT, newSize));
if (Math.abs(newSize - this.fontSize()) > 0.01) {
this.fontSize.set(newSize);
// Sync back to player if display is touched
this.channel.postMessage({ type: 'SYNC_FONT', fontSize: this.fontSize() });
}
}
}
onTouchEnd() {
this.initialPinchDistance = null;
}
private getDistance(t1: Touch, t2: Touch): number {
return Math.sqrt(Math.pow(t1.clientX - t2.clientX, 2) + Math.pow(t1.clientY - t2.clientY, 2));
}
// ----------------------------------------
}
@@ -0,0 +1,17 @@
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { PlayerPage } from './player.page';
const routes: Routes = [
{
path: '',
component: PlayerPage
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class PlayerPageRoutingModule {}
+21
View File
@@ -0,0 +1,21 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { DragDropModule } from '@angular/cdk/drag-drop';
import { IonicModule } from '@ionic/angular';
import { PlayerPageRoutingModule } from './player-routing.module';
import { PlayerPage } from './player.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
PlayerPageRoutingModule,
DragDropModule
],
declarations: [PlayerPage]
})
export class PlayerPageModule {}
+211
View File
@@ -0,0 +1,211 @@
<ion-header [translucent]="true" class="ion-no-border">
<ion-toolbar class="bg-gradient top-toolbar">
<ion-buttons slot="start">
<div class="offline-badge-header" *ngIf="!connectivityService.isOnline()">
<ion-icon name="cloud-offline-outline"></ion-icon>
</div>
</ion-buttons>
<ion-title class="outfit-font wrapped-title">
<div class="title-main" [style.fontSize.rem]="fontSize() * 1.1">
<span class="canto-number" *ngIf="canto()?.id_canti">{{ canto()?.id_canti }}</span>
<span class="title-text">{{ canto()?.titolo || 'Player' }}</span>
</div>
</ion-title>
<ion-buttons slot="start">
<ion-back-button text="" defaultHref="/home" color="secondary"></ion-back-button>
</ion-buttons>
</ion-toolbar>
<!-- Audio Toolbar Removed -->
</ion-header>
<ion-content class="bg-gradient" [class.full-screen-content]="settingsService.fullscreenMode()">
<div class="lyrics-container"
[style.fontSize.rem]="fontSize()"
[class.full-screen-container]="settingsService.fullscreenMode()"
(touchstart)="onTouchStart($event)"
(touchmove)="onTouchMove($event)"
(touchend)="onTouchEnd()">
<!-- Landscape Side Controls (Scrollable) -->
<div class="landscape-side-controls" [class.active-fullscreen]="settingsService.fullscreenMode()">
<div class="side-scroll-container">
<div class="side-group equidistant-group">
<!-- Navigation -->
<ion-button fill="clear" (click)="restart()">
<ion-icon name="arrow-up-circle" color="secondary"></ion-icon>
</ion-button>
<ion-button fill="clear" (click)="prev()" [disabled]="currentLineIndex() === 0">
<ion-icon name="chevron-up" color="secondary"></ion-icon>
</ion-button>
<ion-button fill="clear" (click)="next()" [disabled]="currentLineIndex() === getTotalLines() - 1">
<ion-icon name="chevron-down" color="secondary"></ion-icon>
</ion-button>
<!-- Zoom -->
<ion-button fill="clear" (click)="zoomIn()" [disabled]="fontSize() >= 5.0">
<ion-icon name="add-circle-outline" color="secondary"></ion-icon>
</ion-button>
<ion-button fill="clear" (click)="zoomOut()" [disabled]="fontSize() <= 0.6">
<ion-icon name="remove-circle-outline" color="secondary"></ion-icon>
</ion-button>
<!-- Karaoke Toggle (Moved down) -->
<ion-button fill="clear" (click)="toggleListening()" [color]="audioEngine.isListening() ? 'danger' : 'secondary'">
<ion-icon [name]="audioEngine.isListening() ? 'mic' : 'mic-off'"></ion-icon>
</ion-button>
<!-- Youtube Link -->
<ion-button *ngIf="canto()?.link_youtube && canto()?.link_youtube!.length > 5" fill="clear" (click)="openYoutube()">
<ion-icon name="logo-youtube" color="danger"></ion-icon>
</ion-button>
</div>
</div>
</div>
<!-- Sections rendering -->
<div class="lyrics-view">
<div *ngFor="let section of parsedSections(); let si = index"
class="section"
[class.chorus]="section.type === 'chorus'"
[class.verse-num]="section.type === 'verse_num'">
<!-- Section label for chorus -->
<div *ngIf="section.type === 'chorus'" class="section-label">Rit.</div>
<div *ngIf="section.type === 'verse_num' && section.verseNumber" class="section-label verse-num-label">{{ section.verseNumber }}.</div>
<div *ngFor="let line of section.lines; let li = index"
class="lyric-line"
[class.active]="isActiveLine(si, li)">
<!-- Chord mode: show chords above text -->
<ng-container *ngIf="showChords(); else textOnly">
<span *ngFor="let seg of line.segments" class="chord-segment">
<span *ngIf="seg.chord" class="chord">{{ seg.chord }}</span>
<span class="seg-text">{{ seg.text }}</span>
</span>
</ng-container>
<!-- Text only mode -->
<ng-template #textOnly>
{{ line.text }}
</ng-template>
</div>
</div>
</div>
</div>
</ion-content>
<ion-footer class="ion-no-border">
<!-- Audio Player Toolbar -->
<ion-toolbar class="global-player-toolbar glass" *ngIf="canto()?.link_youtube && canto()?.link_youtube!.length > 5 && !settingsService.fullscreenMode()">
<div class="player-content">
<div class="controls-row">
<ion-button fill="clear" color="secondary" (click)="prevSong()" class="skip-btn">
<ion-icon slot="icon-only" name="play-skip-back-sharp"></ion-icon>
</ion-button>
<ion-button fill="clear" color="secondary" (click)="toggleAudio()" class="play-btn">
<ion-icon slot="icon-only" [name]="youtubePlayerService.isPlaying() ? 'pause-sharp' : 'play-sharp'"></ion-icon>
</ion-button>
<ion-range
[min]="0"
[max]="youtubePlayerService.videoDuration()"
[value]="youtubePlayerService.videoProgress()"
(ionChange)="onSeek($event)"
color="secondary"
class="global-range">
</ion-range>
<ion-button fill="clear" color="secondary" (click)="nextSong()" class="skip-btn">
<ion-icon slot="icon-only" name="play-skip-forward-sharp"></ion-icon>
</ion-button>
<ion-button fill="clear" color="medium" (click)="stopVideo($event)" class="close-btn">
<ion-icon slot="icon-only" name="close-circle-outline"></ion-icon>
</ion-button>
</div>
</div>
</ion-toolbar>
<!-- Voice Activity Visualizer (Slim overlay) -->
<div class="transcript-area slim" *ngIf="audioEngine.isListening()">
<div class="energy-bar" [style.width.%]="math.min(100, audioEngine.energyLevel() * 3)"></div>
</div>
<ion-toolbar class="bg-gradient slim-toolbar">
<div class="slim-controls">
<!-- Karaoke Toggle in Portrait -->
<ion-button fill="clear" size="small" (click)="toggleListening()" [color]="audioEngine.isListening() ? 'danger' : 'secondary'" class="mic-btn-portrait">
<ion-icon slot="icon-only" [name]="audioEngine.isListening() ? 'mic' : 'mic-off'"></ion-icon>
</ion-button>
<!-- Transposition (Only in chords mode) -->
<div class="group" *ngIf="showChords()">
<ion-button fill="clear" size="small" (click)="transposeDown()">
<ion-icon slot="icon-only" name="remove"></ion-icon>
</ion-button>
<div class="transpose-indicator">
<ion-icon name="musical-note" color="secondary"></ion-icon>
<span class="val" *ngIf="transposeAmount() !== 0">{{ transposeAmount() > 0 ? '+' : '' }}{{ transposeAmount() }}</span>
</div>
<ion-button fill="clear" size="small" (click)="transposeUp()">
<ion-icon slot="icon-only" name="add"></ion-icon>
</ion-button>
</div>
<!-- Navigation -->
<div class="group">
<ion-button fill="clear" size="small" (click)="restart()">
<ion-icon slot="icon-only" name="arrow-up-circle" color="secondary"></ion-icon>
</ion-button>
<ion-button fill="clear" size="small" (click)="prev()" [disabled]="currentLineIndex() === 0">
<ion-icon slot="icon-only" name="chevron-back" color="secondary"></ion-icon>
</ion-button>
<ion-button fill="clear" size="small" (click)="next()" [disabled]="currentLineIndex() === getTotalLines() - 1">
<ion-icon slot="icon-only" name="chevron-forward" color="secondary"></ion-icon>
</ion-button>
</div>
<!-- Zoom -->
<div class="group">
<ion-button fill="clear" size="small" (click)="zoomOut()" [disabled]="fontSize() <= 0.6">
<ion-icon slot="icon-only" name="remove-circle-outline" color="secondary"></ion-icon>
</ion-button>
<ion-button fill="clear" size="small" (click)="zoomIn()" [disabled]="fontSize() >= 5.0">
<ion-icon slot="icon-only" name="add-circle-outline" color="secondary"></ion-icon>
</ion-button>
</div>
<!-- Actions -->
<div class="group">
<ion-button *ngIf="canto()?.link_youtube && canto()?.link_youtube!.length > 5" fill="clear" size="small" (click)="openYoutube()">
<ion-icon slot="icon-only" name="logo-youtube" color="danger"></ion-icon>
</ion-button>
</div>
</div>
</ion-toolbar>
</ion-footer>
<!-- Vertical Sensitivity Slider Overlay -->
<div class="mic-sensitivity-overlay" *ngIf="showSensitivitySlider() && audioEngine.isListening()">
<div class="slider-card glass">
<ion-button fill="clear" color="secondary" (click)="toggleSensitivitySlider($event)" class="close-slider-btn">
<ion-icon name="close-outline"></ion-icon>
</ion-button>
<div class="slider-wrapper"
(touchstart)="handleSensitivityTouch($event)"
(touchmove)="handleSensitivityTouch($event)">
<div class="custom-vertical-slider">
<div class="slider-track"></div>
<div class="slider-fill" [style.height.%]="(audioEngine.sensitivity() - 50) * 2"></div>
<div class="slider-knob" [style.bottom.%]="(audioEngine.sensitivity() - 50) * 2"></div>
</div>
</div>
<span class="sensitivity-label outfit-font">{{ audioEngine.sensitivity() }}%</span>
</div>
</div>
+439
View File
@@ -0,0 +1,439 @@
.bg-gradient {
--background: radial-gradient(circle at top left, #2d3436 0%, #121212 100%);
background: radial-gradient(circle at top left, #2d3436 0%, #121212 100%);
}
.outfit-font {
font-family: 'Outfit', sans-serif;
}
// Header styles
.top-toolbar {
--padding-top: 4px;
--padding-bottom: 4px;
--min-height: 40px;
// Force left alignment in Ionic toolbar
ion-title {
padding-inline: 8px;
text-align: left !important;
}
.title-main {
display: flex;
align-items: center;
justify-content: flex-start;
gap: 12px;
font-weight: 700;
color: var(--ion-color-secondary);
white-space: normal;
line-height: 1.2;
text-align: left;
.canto-number {
font-size: 0.85em;
background: rgba(var(--ion-color-secondary-rgb), 0.15);
padding: 2px 10px;
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: 6px;
border: 1px solid rgba(var(--ion-color-secondary-rgb), 0.3);
flex-shrink: 0;
&.clickable {
cursor: pointer;
transition: all 0.2s ease;
&:active { transform: scale(0.9); }
}
&.selected {
background: var(--ion-color-secondary);
color: #000;
border-color: var(--ion-color-secondary);
box-shadow: 0 0 10px rgba(var(--ion-color-secondary-rgb), 0.4);
}
}
.title-text {
flex: 1;
text-align: left;
}
}
}
// Content and Lyrics
.lyrics-container {
padding: 8px 24px 140px 24px; // Increased bottom padding for global player
height: 100%;
overflow-y: auto;
scroll-behavior: smooth;
-webkit-overflow-scrolling: touch;
&.full-screen-container {
padding-bottom: 20px !important;
}
}
// ... existing code ...
/* GLOBAL PLAYER FOOTER */
.global-player-toolbar {
--background: transparent;
--padding-top: 4px;
--padding-bottom: 4px;
--padding-start: 12px;
--padding-end: 12px;
&.glass {
background: rgba(26, 26, 46, 0.95) !important;
backdrop-filter: blur(20px);
border-top: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 0 !important;
box-shadow: none !important;
}
.player-content {
display: flex;
flex-direction: column;
padding: 0;
}
.controls-row {
display: flex;
align-items: center;
gap: 4px;
.play-btn {
--padding-start: 0;
--padding-end: 0;
height: 44px;
width: 44px;
ion-icon {
font-size: 2.2rem;
}
}
.skip-btn, .close-btn {
--padding-start: 0;
--padding-end: 0;
height: 36px;
width: 36px;
ion-icon {
font-size: 1.4rem;
}
}
.global-range {
flex: 1;
--bar-height: 4px;
--knob-size: 14px;
padding-top: 0;
padding-bottom: 0;
}
}
}
.lyrics-view {
max-width: 900px;
margin-left: 0; // Always left aligned
text-align: left;
}
.section {
margin-bottom: 2rem;
position: relative;
&.chorus {
background: rgba(var(--ion-color-secondary-rgb), 0.03);
border-left: 3px solid var(--ion-color-secondary);
padding-left: 1rem;
margin-left: -1rem;
border-radius: 0 8px 8px 0;
}
.section-label {
font-size: 0.7rem;
text-transform: uppercase;
font-weight: 700;
color: var(--ion-color-secondary);
margin-bottom: 0.5rem;
opacity: 0.7;
letter-spacing: 1px;
}
}
.lyric-line {
margin-bottom: 1rem;
line-height: 1.6;
color: rgba(255, 255, 255, 0.9);
transition: all 0.3s ease;
min-height: 1.5em;
&.active {
color: var(--ion-color-secondary);
font-weight: 700;
transform: scale(1.02);
text-shadow: 0 0 15px rgba(var(--ion-color-secondary-rgb), 0.3);
}
}
.chord-segment {
display: inline-flex;
flex-direction: column;
vertical-align: bottom;
margin-right: 0.2em;
.chord {
font-size: 0.75em;
font-weight: 700;
color: var(--ion-color-secondary);
height: 1.2em;
margin-bottom: -0.2em;
}
.seg-text {
white-space: pre;
}
}
// Footer styles
.slim-toolbar {
--min-height: 48px;
backdrop-filter: blur(15px);
background: rgba(0,0,0,0.4) !important;
}
.slim-controls {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
padding: 0 8px;
.group {
display: flex;
align-items: center;
gap: 4px;
background: rgba(255, 255, 255, 0.05);
padding: 2px 6px;
border-radius: 12px;
border: 1px solid rgba(255, 255, 255, 0.1);
}
.page-indicator {
font-size: 0.8rem;
font-weight: 700;
color: var(--ion-color-secondary);
min-width: 40px;
text-align: center;
}
.transpose-indicator {
display: flex;
align-items: center;
gap: 2px;
font-size: 0.8rem;
font-weight: 700;
color: var(--ion-color-secondary);
ion-icon { font-size: 0.9rem; }
}
}
// Transcript area
.transcript-area {
height: 4px;
width: 100%;
background: rgba(0,0,0,0.2);
.energy-bar {
height: 100%;
background: var(--ion-color-danger);
transition: width 0.1s ease;
box-shadow: 0 0 10px var(--ion-color-danger);
}
}
// Fullscreen and Orientation
@media (orientation: landscape) {
// Always hide footer in landscape as we have side controls
ion-footer {
display: none !important;
}
.lyrics-container {
height: 100%;
padding-top: 4px; // Minimized
padding-right: 90px !important; // More room for side controls and zoom
}
ion-content {
--offset-bottom: 0px !important;
}
}
ion-content.full-screen-content {
--offset-bottom: 0px !important;
@media (orientation: portrait) {
--offset-bottom: 48px !important; // Footer height
}
}
.landscape-side-controls {
display: none !important; // Strict hidden in portrait
@media (orientation: landscape) {
display: flex !important;
flex-direction: column;
position: fixed;
right: 0;
top: 44px !important; // Align with header
bottom: 0;
width: 60px;
background: rgba(0, 0, 0, 0.3);
backdrop-filter: blur(10px);
border-left: 1px solid rgba(255, 255, 255, 0.1);
z-index: 100;
}
.side-scroll-container {
height: 100%;
overflow-y: auto;
display: flex;
flex-direction: column;
padding: 12px 0;
gap: 16px;
&::-webkit-scrollbar { display: none; }
}
.side-group {
display: flex;
flex-direction: column;
align-items: center;
gap: 10px; // Reduced for a more compact layout
padding-bottom: 20px;
ion-button {
--padding-start: 0;
--padding-end: 0;
margin: 0;
height: 48px;
ion-icon { font-size: 1.8rem; }
}
}
.side-divider {
display: none;
}
}
.mic-sensitivity-overlay {
position: fixed;
right: 15px;
top: 50%;
transform: translateY(-50%);
z-index: 1000;
pointer-events: auto;
@media (orientation: landscape) {
right: 80px; // Prossimo ai controlli laterali
}
.slider-card {
display: flex;
flex-direction: column;
align-items: center;
padding: 8px 6px 12px 6px;
background: rgba(18, 18, 18, 0.85) !important;
backdrop-filter: blur(25px);
border-radius: 24px;
border: 1px solid rgba(var(--ion-color-secondary-rgb), 0.4);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.6);
gap: 12px;
animation: slideInRight 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
.close-slider-btn {
--padding-start: 0;
--padding-end: 0;
margin: 0;
height: 36px;
width: 36px;
--color: var(--ion-color-secondary);
ion-icon {
font-size: 1.5rem;
}
}
.slider-wrapper {
height: 180px;
width: 40px;
display: flex;
align-items: center;
justify-content: center;
position: relative;
padding: 10px 0;
}
.custom-vertical-slider {
position: relative;
width: 8px;
height: 100%;
background: rgba(255, 255, 255, 0.1);
border-radius: 4px;
.slider-track {
position: absolute;
width: 100%;
height: 100%;
}
.slider-fill {
position: absolute;
bottom: 0;
width: 100%;
background: var(--ion-color-secondary);
border-radius: 4px;
box-shadow: 0 0 10px rgba(var(--ion-color-secondary-rgb), 0.3);
transition: height 0.05s linear;
}
.slider-knob {
position: absolute;
left: 50%;
transform: translate(-50%, 50%);
width: 28px;
height: 28px;
background: var(--ion-color-secondary);
border-radius: 50%;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.5), 0 0 15px rgba(var(--ion-color-secondary-rgb), 0.5);
border: 2px solid #fff;
transition: bottom 0.05s linear;
}
}
.sensitivity-label {
font-size: 0.8rem;
font-weight: 800;
color: var(--ion-color-secondary);
min-width: 40px;
text-align: center;
letter-spacing: 0.5px;
}
}
@keyframes slideInRight {
from {
opacity: 0;
transform: translateX(20px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
+17
View File
@@ -0,0 +1,17 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { PlayerPage } from './player.page';
describe('PlayerPage', () => {
let component: PlayerPage;
let fixture: ComponentFixture<PlayerPage>;
beforeEach(() => {
fixture = TestBed.createComponent(PlayerPage);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
+489
View File
@@ -0,0 +1,489 @@
import { Component, OnInit, OnDestroy, signal, computed, effect, inject, ElementRef, AfterViewInit } from '@angular/core';
import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import { AlertController, ToastController, GestureController } from '@ionic/angular';
import { CantiService, Canto } from '../../services/canti.service';
import { AudioEngineService } from '../../services/audio-engine.service';
import { LyricsParserService, ParsedSection } from '../../services/lyrics-parser.service';
import { ThemeService } from '../../services/theme.service';
import { SettingsService } from '../../services/settings.service';
import { ConnectivityService } from '../../services/connectivity.service';
import { PlaylistService } from '../../services/playlist.service';
import { YoutubePlayerService } from '../../services/youtube-player.service';
import { MyCantiService } from '../../services/my-canti.service';
@Component({
selector: 'app-player',
templateUrl: './player.page.html',
styleUrls: ['./player.page.scss'],
standalone: false
})
export class PlayerPage implements OnInit, AfterViewInit, OnDestroy {
public canto = signal<Canto | null>(null);
/** true = show chords (accordi mode), false = text only */
public showChords = signal<boolean>(false);
public showSensitivitySlider = signal<boolean>(false);
/** Font size scale factor (1.0 = default) */
public fontSize = signal<number>(1.0);
/** Parsed sections for the current view mode */
public parsedSections = computed<ParsedSection[]>(() => {
const c = this.canto();
if (!c) return [];
let sections: ParsedSection[];
// For local songs, if accordi is missing but testo has chords, use parseAccordi on testo
const hasChordsInText = !c.accordi && c.testo?.includes('[');
if ((this.showChords() && c.accordi) || (this.showChords() && hasChordsInText)) {
sections = this.lyricsParser.parseAccordi(c.accordi || c.testo);
} else {
sections = this.lyricsParser.parseText(c.testo);
}
// CRITICAL FIX: If sections are empty but we have text, force a manual section
if (sections.length === 0 && c.testo) {
const fallbackLines = c.testo.split('\n')
.filter(l => l.trim().length > 0)
.map(l => ({
text: l.trim(),
segments: [{ text: l.trim() }]
}));
if (fallbackLines.length > 0) {
sections = [{
type: 'verse',
lines: fallbackLines
}];
}
}
// Apply transposition if in chords mode
if (this.showChords() && this.transposeAmount() !== 0) {
return this.lyricsParser.transposeSections(sections, this.transposeAmount());
}
return sections;
});
public transposeAmount = signal<number>(0);
public currentLineIndex = signal<number>(0);
public math = Math;
public youtubePlayerService = inject(YoutubePlayerService);
private channel = new BroadcastChannel('karaoke_sync');
private readonly MIN_FONT = 0.6;
private readonly MAX_FONT = 5.0;
private readonly FONT_STEP = 0.15;
private initialPinchDistance: number | null = null;
private initialFontSize: number = 1.0;
private lastMatchedTranscript: string = '';
// --- Logic State ---
private lastAdvanceTimestamp: number = 0; // For safety cooldown
private readonly ADVANCE_COOLDOWN = 1500; // 1.5 seconds min
private wordsSpokenInCurrentLine: number = 0;
private lastProcessedTranscript: string = '';
private initialStartTime: number = 0;
private route = inject(ActivatedRoute);
public router = inject(Router);
public cantiService = inject(CantiService);
public audioEngine = inject(AudioEngineService);
private lyricsParser = inject(LyricsParserService);
private alertCtrl = inject(AlertController);
private toastCtrl = inject(ToastController);
public themeService = inject(ThemeService);
public settingsService = inject(SettingsService);
public connectivityService = inject(ConnectivityService);
public playlistService = inject(PlaylistService);
private myCantiService = inject(MyCantiService);
private gestureCtrl = inject(GestureController);
private el = inject(ElementRef);
private sanitizer = inject(DomSanitizer);
constructor() {
// Sync mode from global settings
effect(() => {
this.showChords.set(this.settingsService.showChordsDefault());
}, { allowSignalWrites: true });
// Automatic advancement logic based on line detection
effect(() => {
const count = this.audioEngine.linesDetected();
if (count > 0) {
this.next();
}
});
// Auto-scroll logic: keep active line in view
effect(() => {
const idx = this.currentLineIndex();
// Wait for DOM update
setTimeout(() => {
const activeElem = document.querySelector('.lyric-line.active');
if (activeElem) {
activeElem.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}, 100);
});
effect(() => {
const c = this.canto();
if (c) {
if (this.playlistService.autoPlayPlaylist()) {
setTimeout(() => this.initPlayer(c.id), 500);
}
}
});
}
ngAfterViewInit() {
const gesture = this.gestureCtrl.create({
el: this.el.nativeElement,
direction: 'x',
gestureName: 'swipe-song',
canStart: (ev) => {
// Prevent swipe when touching the bottom toolbar or other interactive elements
const target = ev.event.target as HTMLElement;
return !target.closest('ion-footer');
},
onEnd: (ev) => {
if (Math.abs(ev.deltaX) > 60) {
if (ev.deltaX > 0) {
this.prevSong();
} else {
this.nextSong();
}
}
}
});
gesture.enable();
}
private getAllLines(): any[] {
const sections = this.parsedSections();
const allLines: any[] = [];
for (const s of sections) {
for (const l of s.lines) {
allLines.push(l);
}
}
return allLines;
}
ngOnInit() {
this.route.queryParams.subscribe(async params => {
let id = params['id'];
if (params['t']) {
this.initialStartTime = parseInt(params['t'], 10);
}
if (!id) {
id = await this.cantiService.getStorage()?.get('last_song_id');
}
if (id) {
let found: Canto | undefined = this.cantiService.getCantoById(id);
if (!found) {
found = this.myCantiService.myCanti().find(c => c.id === id);
}
if (found) {
this.canto.set(found);
this.cantiService.getStorage()?.set('last_song_id', id);
this.channel.postMessage({ type: 'SYNC_CANTO', id: found.id });
}
}
});
}
onTouchStart(event: TouchEvent) {
if (event.touches.length === 2) {
this.initialPinchDistance = this.getDistance(event.touches[0], event.touches[1]);
this.initialFontSize = this.fontSize();
}
}
onTouchMove(event: TouchEvent) {
if (event.touches.length === 2 && this.initialPinchDistance !== null) {
event.preventDefault();
const currentDistance = this.getDistance(event.touches[0], event.touches[1]);
const ratio = currentDistance / this.initialPinchDistance;
let newSize = this.initialFontSize * ratio;
newSize = Math.max(this.MIN_FONT, Math.min(this.MAX_FONT, newSize));
if (Math.abs(newSize - this.fontSize()) > 0.01) {
this.fontSize.set(newSize);
this.channel.postMessage({ type: 'SYNC_FONT', fontSize: this.fontSize() });
}
}
}
onTouchEnd() {
this.initialPinchDistance = null;
}
private getDistance(t1: Touch, t2: Touch): number {
return Math.sqrt(Math.pow(t1.clientX - t2.clientX, 2) + Math.pow(t1.clientY - t2.clientY, 2));
}
toggleChords() {
this.showChords.update(v => !v);
this.channel.postMessage({ type: 'SYNC_CHORDS', showChords: this.showChords() });
this.transposeAmount.set(0);
}
transposeUp() {
this.transposeAmount.update(v => v + 1);
this.channel.postMessage({ type: 'SYNC_TRANSPOSE', amount: this.transposeAmount() });
}
transposeDown() {
this.transposeAmount.update(v => v - 1);
this.channel.postMessage({ type: 'SYNC_TRANSPOSE', amount: this.transposeAmount() });
}
zoomIn() {
if (this.fontSize() < this.MAX_FONT) {
this.fontSize.update(v => Math.min(v + this.FONT_STEP, this.MAX_FONT));
this.channel.postMessage({ type: 'SYNC_FONT', fontSize: this.fontSize() });
}
}
zoomOut() {
if (this.fontSize() > this.MIN_FONT) {
this.fontSize.update(v => Math.max(v - this.FONT_STEP, this.MIN_FONT));
this.channel.postMessage({ type: 'SYNC_FONT', fontSize: this.fontSize() });
}
}
toggleListening() {
if (this.audioEngine.isListening()) {
this.audioEngine.stopListening();
this.showSensitivitySlider.set(false);
} else {
this.audioEngine.startListening();
this.showSensitivitySlider.set(true);
}
}
toggleSensitivitySlider(event: Event) {
event.stopPropagation();
this.showSensitivitySlider.update(v => !v);
}
onSensitivityChange(event: any) {
this.audioEngine.sensitivity.set(event.detail.value);
}
handleSensitivityTouch(event: TouchEvent) {
event.preventDefault();
const touch = event.touches[0];
const target = event.currentTarget as HTMLElement;
const rect = target.getBoundingClientRect();
// Calculate percentage based on Y position (bottom is 50%, top is 100%)
const rawPercentage = 100 - ((touch.clientY - rect.top) / rect.height * 100);
// Map 0-100 raw to 50-100 range
let percentage = 50 + (rawPercentage * 0.5);
percentage = Math.max(50, Math.min(100, Math.round(percentage)));
this.audioEngine.sensitivity.set(percentage);
}
toggleAudio() {
if (this.youtubePlayerService.currentCantoId() === this.canto()?.id) {
this.youtubePlayerService.togglePlayPause();
} else {
const c = this.canto();
if (c) {
this.playlistService.autoPlayPlaylist.set(true);
this.initPlayer(c.id);
}
}
}
stopVideo(event?: Event) {
if (event) event.stopPropagation();
this.youtubePlayerService.stop();
this.playlistService.autoPlayPlaylist.set(false);
}
onSeek(event: any) {
this.youtubePlayerService.seekTo(event.detail.value);
}
restart() {
this.currentLineIndex.set(0);
this.audioEngine.resetWordCount();
this.youtubePlayerService.seekTo(0);
this.channel.postMessage({ type: 'SYNC_INDEX', index: 0 });
}
next() {
this.lastAdvanceTimestamp = Date.now();
this.audioEngine.resetWordCount();
const totalLines = this.getTotalLines();
if (this.currentLineIndex() < totalLines - 1) {
this.currentLineIndex.set(this.currentLineIndex() + 1);
this.channel.postMessage({ type: 'SYNC_INDEX', index: this.currentLineIndex() });
}
}
prev() {
this.lastAdvanceTimestamp = Date.now();
this.audioEngine.resetWordCount();
if (this.currentLineIndex() > 0) {
this.currentLineIndex.set(this.currentLineIndex() - 1);
this.channel.postMessage({ type: 'SYNC_INDEX', index: this.currentLineIndex() });
}
}
nextSong() {
let list = this.playlistService.activeListIds();
if (list.length === 0) {
list = this.cantiService.canti().map(c => c.id);
}
const currentId = this.canto()?.id;
if (!currentId) return;
const index = list.indexOf(currentId);
if (index >= 0 && index < list.length - 1) {
const nextId = list[index + 1];
this.router.navigate(['/player'], { queryParams: { id: nextId } });
} else {
this.playlistService.autoPlayPlaylist.set(false);
}
}
prevSong() {
let list = this.playlistService.activeListIds();
if (list.length === 0) {
list = this.cantiService.canti().map(c => c.id);
}
const currentId = this.canto()?.id;
if (!currentId) return;
const index = list.indexOf(currentId);
if (index > 0) {
const prevId = list[index - 1];
this.router.navigate(['/player'], { queryParams: { id: prevId } });
}
}
private goToSong(id: string) {
this.router.navigate([], {
relativeTo: this.route,
queryParams: { id },
queryParamsHandling: 'merge'
});
this.restart();
}
getTotalLines(): number {
return this.parsedSections().reduce((acc, s) => acc + s.lines.length, 0);
}
isActiveLine(sectionIdx: number, lineIdx: number): boolean {
let flatIdx = 0;
for (let s = 0; s < this.parsedSections().length; s++) {
for (let l = 0; l < this.parsedSections()[s].lines.length; l++) {
if (s === sectionIdx && l === lineIdx) {
return flatIdx === this.currentLineIndex();
}
flatIdx++;
}
}
return false;
}
async openDisplay() {
const url = this.router.serializeUrl(
this.router.createUrlTree(['/display'], { queryParams: { id: this.canto()?.id } })
);
const absoluteUrl = window.location.origin + window.location.pathname + url;
const win = window.open(absoluteUrl, '_blank', 'width=1024,height=768');
if (!win) {
const alert = await this.alertCtrl.create({
header: 'Proiezione TV',
message: 'Il browser ha bloccato l\'apertura della finestra. Vuoi copiare il link da inviare alla TV?',
buttons: [
{ text: 'Annulla', role: 'cancel' },
{ text: 'Copia Link', handler: () => { this.copyToClipboard(absoluteUrl); } }
]
});
await alert.present();
}
}
async copyToClipboard(text: string) {
try {
await navigator.clipboard.writeText(text);
const toast = await this.toastCtrl.create({
message: 'Link copiato negli appunti!',
duration: 2000,
position: 'top',
color: 'secondary'
});
await toast.present();
} catch (err) {}
}
openYoutube() {
const videoId = this.cantiService.getYoutubeId(this.canto()?.link_youtube);
if (videoId) {
window.open(`https://www.youtube.com/watch?v=${videoId}`, '_blank');
}
}
private initPlayer(id: string) {
const startT = this.initialStartTime;
this.initialStartTime = 0; // Reset
this.youtubePlayerService.setMediaSessionCallbacks(
() => this.nextSong(),
() => this.prevSong()
);
this.youtubePlayerService.initPlayer(
id,
startT,
() => {
if (this.playlistService.autoPlayPlaylist() && this.settingsService.autoAdvance()) {
this.nextSong();
} else {
this.playlistService.autoPlayPlaylist.set(false);
}
},
() => {
if (this.playlistService.autoPlayPlaylist() && this.settingsService.autoAdvance()) {
setTimeout(() => this.nextSong(), 1000);
} else {
this.playlistService.autoPlayPlaylist.set(false);
}
}
);
}
togglePlaylistSelection() {
const c = this.canto();
if (c) {
this.playlistService.toggleSongSelection(c.id);
}
}
ngOnDestroy() {
this.audioEngine.stopListening();
this.channel.close();
}
}
+26
View File
@@ -0,0 +1,26 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { DragDropModule } from '@angular/cdk/drag-drop';
import { PlaylistPage } from './playlist.page';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{
path: '',
component: PlaylistPage
}
];
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
DragDropModule,
RouterModule.forChild(routes)
],
declarations: [PlaylistPage]
})
export class PlaylistPageModule {}
+43
View File
@@ -0,0 +1,43 @@
<ion-header class="ion-no-border">
<ion-toolbar class="bg-gradient">
<ion-buttons slot="start">
<ion-back-button defaultHref="/home" color="secondary"></ion-back-button>
</ion-buttons>
<ion-title class="outfit-font">Gestione Playlist</ion-title>
<ion-buttons slot="end">
<ion-button (click)="savePlaylist()" [disabled]="localSongs.length === 0">
<ion-icon slot="icon-only" name="save-outline"></ion-icon>
</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content class="bg-gradient">
<div class="ion-padding">
<div class="header-info glass ion-margin-bottom" *ngIf="localSongs.length > 0">
<p>Trascina i canti per riordinarli. Una volta finito puoi salvare la playlist.</p>
</div>
<div cdkDropList class="song-list" (cdkDropListDropped)="drop($event)">
<div class="song-item glass ion-margin-bottom" *ngFor="let song of localSongs" cdkDrag>
<div class="drag-handle" cdkDragHandle>
<ion-icon name="reorder-two-outline"></ion-icon>
</div>
<div class="song-info">
<span class="canto-number">{{ song.id_canti }}</span>
<span class="song-title">{{ song.titolo }}</span>
</div>
<div class="example-custom-placeholder" *cdkDragPlaceholder></div>
</div>
</div>
<div *ngIf="localSongs.length === 0" class="empty-state ion-text-center">
<ion-icon name="musical-notes-outline" class="large-icon"></ion-icon>
<p>Nessun canto selezionato.</p>
<ion-button routerLink="/home" fill="outline" color="secondary" class="ion-margin-top">
Torna alla Home
</ion-button>
</div>
</div>
</ion-content>
+179
View File
@@ -0,0 +1,179 @@
.song-list {
display: block;
}
.song-item {
display: flex;
align-items: center;
padding: 12px;
border-radius: 12px;
cursor: move;
background: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.1);
.drag-handle {
margin-right: 12px;
color: rgba(255, 255, 255, 0.3);
font-size: 1.5rem;
display: flex;
align-items: center;
}
.song-info {
display: flex;
align-items: center;
gap: 8px;
.canto-number {
background: rgba(var(--ion-color-secondary-rgb), 0.1);
color: var(--ion-color-secondary);
padding: 2px 6px;
border-radius: 4px;
font-size: 0.8rem;
font-weight: 700;
}
.song-title {
font-weight: 500;
color: white;
}
}
}
.cdk-drag-preview {
box-sizing: border-box;
border-radius: 4px;
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);
background: #1e1e1e;
padding: 12px;
display: flex;
align-items: center;
color: white;
}
.cdk-drag-placeholder {
opacity: 0;
}
.cdk-drag-animating {
transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
}
.song-list.cdk-drop-list-dragging .song-item:not(.cdk-drag-placeholder) {
transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
}
.header-info {
padding: 12px;
border-radius: 12px;
p {
margin: 0;
font-size: 0.9rem;
color: rgba(255, 255, 255, 0.7);
line-height: 1.4;
}
}
.empty-state {
margin-top: 100px;
.large-icon {
font-size: 5rem;
color: rgba(255, 255, 255, 0.1);
}
p {
color: rgba(255, 255, 255, 0.5);
margin-top: 16px;
}
}
.qr-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.8);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
backdrop-filter: blur(5px);
.qr-card {
background: #ffffff;
padding: 24px;
border-radius: 20px;
width: 90%;
max-width: 350px;
text-align: center;
color: #000;
.qr-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 16px;
h3 { margin: 0; text-align: left; }
}
p {
font-size: 0.9rem;
color: #666;
margin-bottom: 24px;
text-align: left;
}
.qr-img-container {
background: #f8f8f8;
padding: 16px;
border-radius: 16px;
margin-bottom: 24px;
img {
width: 100%;
height: auto;
display: block;
}
}
.qr-actions {
display: flex;
flex-direction: column;
gap: 8px;
}
}
}
.save-export-fab {
--border-radius: 30px;
width: auto;
min-width: 160px;
.fab-content {
display: flex;
align-items: center;
padding: 0 16px;
gap: 8px;
ion-icon {
font-size: 1.4rem;
}
.fab-label {
font-size: 0.9rem;
font-weight: 600;
text-transform: none;
}
}
}
:host-context(body.high-contrast) {
.song-item {
background: #ffffff !important;
border-color: #000000 !important;
.song-title { color: #000000 !important; }
.drag-handle { color: #000000 !important; }
}
.header-info p { color: #000000 !important; }
}
+180
View File
@@ -0,0 +1,180 @@
import { Component, inject, computed } from '@angular/core';
import { PlaylistService } from '../../services/playlist.service';
import { CantiService } from '../../services/canti.service';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { AlertController, ToastController, ModalController } from '@ionic/angular';
import { Router } from '@angular/router';
@Component({
selector: 'app-playlist',
templateUrl: './playlist.page.html',
styleUrls: ['./playlist.page.scss'],
standalone: false
})
export class PlaylistPage {
public playlistService = inject(PlaylistService);
public cantiService = inject(CantiService);
private alertCtrl = inject(AlertController);
private toastCtrl = inject(ToastController);
private router = inject(Router);
public selectedSongs = computed(() => {
const ids = Array.from(this.playlistService.selectedIds());
return ids.map(id => this.cantiService.canti().find(c => c.id === id)).filter(c => !!c);
});
public localSongs: any[] = [];
public qrCodeImage: string | null = null;
public savedPlaylistName: string | null = null;
constructor() {
// Initial copy to allow local reordering
this.localSongs = [...this.selectedSongs()];
}
drop(event: CdkDragDrop<string[]>) {
moveItemInArray(this.localSongs, event.previousIndex, event.currentIndex);
}
async savePlaylist() {
const alert = await this.alertCtrl.create({
header: 'Salva Playlist',
inputs: [
{
name: 'name',
type: 'text',
placeholder: 'Nome della playlist',
value: this.savedPlaylistName || ''
}
],
buttons: [
{
text: 'Annulla',
role: 'cancel'
},
{
text: 'Salva',
handler: (data) => {
if (data.name) {
this.savedPlaylistName = data.name;
this.playlistService.savePlaylist(data.name, this.localSongs.map(s => s.id));
this.showToast('Playlist salvata!');
this.router.navigate(['/settings']);
return true;
}
return false;
}
}
]
});
await alert.present();
}
async saveAndExport() {
const alert = await this.alertCtrl.create({
header: 'Salva ed Esporta QR',
message: 'Inserisci un nome per la playlist. Verrà salvata e generato il QR Code.',
inputs: [
{
name: 'name',
type: 'text',
placeholder: 'Nome della playlist',
value: this.savedPlaylistName || ''
}
],
buttons: [
{
text: 'Annulla',
role: 'cancel'
},
{
text: 'Salva ed Esporta',
handler: async (data) => {
if (data.name) {
this.savedPlaylistName = data.name;
const ids = this.localSongs.map(s => s.id);
await this.playlistService.savePlaylist(data.name, ids);
this.qrCodeImage = await this.playlistService.generateQR(ids, data.name);
this.showToast('Playlist salvata!');
return true;
}
return false;
}
}
]
});
await alert.present();
}
async sharePlaylist() {
if (this.localSongs.length === 0) return;
const ids = this.localSongs.map(s => s.id);
const name = this.savedPlaylistName || 'Playlist Condivisa';
this.qrCodeImage = await this.playlistService.generateQR(ids, name);
}
downloadQR() {
if (!this.qrCodeImage) return;
const name = this.savedPlaylistName || 'playlist';
const fileName = `${name.toLowerCase().replace(/\s+/g, '_')}_qr.png`;
const link = document.createElement('a');
link.href = this.qrCodeImage;
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
this.showToast('Immagine scaricata!');
}
async shareQR() {
if (!this.qrCodeImage) return;
const name = this.savedPlaylistName || 'playlist';
const shareLink = this.playlistService.getShareLink(this.localSongs.map(s => s.id), name);
const fileName = `${name.toLowerCase().replace(/\s+/g, '_')}_qr.png`;
try {
// Convert base64 to blob/file for sharing
const res = await fetch(this.qrCodeImage);
const blob = await res.blob();
const file = new File([blob], fileName, { type: 'image/png' });
if (navigator.share && navigator.canShare && navigator.canShare({ files: [file] })) {
await navigator.share({
files: [file],
title: 'Playlist CantiCristiani',
text: `Ecco la playlist: ${name}\n\nClicca qui per aprirla subito: ${shareLink}`
});
} else {
// Fallback to simple share text or download
if (navigator.share) {
await navigator.share({
title: 'Playlist CantiCristiani',
text: `Ecco la playlist: ${name}\n\nClicca qui per aprirla: ${shareLink}`
});
} else {
this.downloadQR();
}
}
} catch (err) {
console.error('Share failed', err);
this.downloadQR();
}
}
closeQR() {
this.qrCodeImage = null;
}
async showToast(message: string) {
const toast = await this.toastCtrl.create({
message,
duration: 2000,
color: 'success'
});
await toast.present();
}
}
@@ -0,0 +1,144 @@
<ion-header class="ion-no-border">
<ion-toolbar class="bg-gradient">
<ion-buttons slot="start">
<ion-back-button defaultHref="/home" color="secondary"></ion-back-button>
</ion-buttons>
<ion-title class="outfit-font">Mio Canto</ion-title>
<ion-buttons slot="end">
<ion-button (click)="isHighContrast = !isHighContrast" [color]="isHighContrast ? 'warning' : 'medium'">
<ion-icon slot="icon-only" name="contrast-outline"></ion-icon>
</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content class="ion-padding bg-gradient" [class.high-contrast-mode]="isHighContrast">
<div class="propose-container">
<!-- OCR Progress -->
<div class="ocr-progress-card" *ngIf="isProcessingOCR">
<ion-spinner name="crescent"></ion-spinner>
<div class="progress-info">
<p>Elaborazione in corso...</p>
<ion-progress-bar [value]="ocrProgress" color="secondary"></ion-progress-bar>
</div>
</div>
<ion-list lines="none" class="input-list">
<ion-item class="custom-input-item">
<ion-label position="stacked">Titolo del Canto</ion-label>
<ion-input [(ngModel)]="title" placeholder="Es: Il Signore è la mia salvezza"></ion-input>
</ion-item>
<div class="category-selectors">
<ion-item class="custom-input-item select-item">
<ion-label position="stacked">Momento Liturgico</ion-label>
<ion-select [(ngModel)]="selectedLiturgico" placeholder="Scegli momento" multiple="true" interface="popover">
<ion-select-option *ngFor="let lit of cantiService.indiceLiturgico()" [value]="lit.id">
{{ lit.tag_name }}
</ion-select-option>
</ion-select>
</ion-item>
<ion-item class="custom-input-item select-item">
<ion-label position="stacked">Periodo / Tema</ion-label>
<ion-select [(ngModel)]="selectedTematico" placeholder="Scegli tema" multiple="true" interface="popover">
<ion-select-option *ngFor="let tem of cantiService.indiceTematico()" [value]="tem.id">
{{ tem.tag_name }}
</ion-select-option>
</ion-select>
</ion-item>
</div>
<!-- TOOLBARS -->
<div class="toolbar-section">
<div class="horizontal-toolbar">
<ion-button *ngFor="let tag of commonTags" size="small" fill="outline" (click)="insertText(tag.start)">
{{ tag.label }}
</ion-button>
</div>
</div>
<div class="toolbar-section">
<div class="horizontal-toolbar chords-toolbar">
<ion-button size="small" *ngFor="let chord of commonChords" (click)="insertChord(chord)">
{{ chord }}
</ion-button>
</div>
</div>
<!-- EDITOR AREA -->
<div class="editor-wrapper" [class.hc]="isHighContrast">
<div class="editor-header">
<div class="editor-title-group">
<span>Editor Testo</span>
</div>
<div class="editor-actions">
<ion-button fill="clear" size="small" (click)="undo()" [disabled]="undoStack.length === 0">
<ion-icon name="undo-outline"></ion-icon>
</ion-button>
<ion-button fill="clear" size="small" (click)="takePhoto()">
<ion-icon name="camera-outline"></ion-icon>
</ion-button>
<ion-button fill="clear" size="small" (click)="uploadDoc()">
<ion-icon name="document-text-outline"></ion-icon>
</ion-button>
</div>
</div>
<ion-item class="custom-input-item textarea-item">
<ion-textarea
#contentTextarea
[(ngModel)]="content"
placeholder="Scrivi o scansiona..."
rows="18"
class="content-textarea"
(click)="openQuickMenu($event)">
</ion-textarea>
</ion-item>
</div>
<ion-item class="custom-input-item">
<ion-label position="stacked">Autore / Link YouTube</ion-label>
<ion-input [(ngModel)]="author" placeholder="Autore"></ion-input>
<ion-input [(ngModel)]="youtubeLink" placeholder="URL YouTube"></ion-input>
</ion-item>
</ion-list>
<div class="action-buttons">
<ion-button expand="block" (click)="saveToMyCanti()" class="send-btn" [disabled]="!title || !content || isProcessingOCR">
<ion-icon slot="start" name="save-outline"></ion-icon>
Salva nei Miei Canti
</ion-button>
</div>
</div>
<!-- QUICK INSERT POPOVER -->
<ion-popover [isOpen]="isChordPopoverOpen" (didDismiss)="isChordPopoverOpen = false" class="quick-popover">
<ng-template>
<ion-content class="ion-padding">
<div class="popover-container">
<div class="popover-section">
<h6>Struttura e Tag</h6>
<div class="popover-grid tags-grid">
<ion-button *ngFor="let tag of commonTags" size="small" fill="outline" (click)="insertText(tag.start); isChordPopoverOpen = false">
{{ tag.label }}
</ion-button>
</div>
</div>
<div class="popover-section">
<h6>Accordi Comuni</h6>
<div class="popover-grid chords-grid">
<ion-button *ngFor="let chord of commonChords" size="small" (click)="insertChord(chord); isChordPopoverOpen = false">
{{ chord }}
</ion-button>
</div>
</div>
</div>
</ion-content>
</ng-template>
</ion-popover>
<!-- Hidden inputs -->
<input type="file" #cameraInput (change)="onFileSelected($event, true)" accept="image/*" capture="camera" style="display: none;">
<input type="file" #docInput (change)="onFileSelected($event, false)" accept=".pdf,.docx,.txt,.odt" style="display: none;">
</ion-content>
@@ -0,0 +1,283 @@
.bg-gradient {
--background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
}
.propose-container {
max-width: 800px;
margin: 0 auto;
}
.ocr-progress-card {
background: rgba(var(--ion-color-secondary-rgb), 0.15);
border: 1px solid var(--ion-color-secondary);
border-radius: 16px;
padding: 20px;
display: flex;
align-items: center;
gap: 16px;
margin-bottom: 20px;
box-shadow: 0 4px 15px rgba(0,0,0,0.3);
ion-spinner {
color: var(--ion-color-secondary);
width: 32px;
height: 32px;
}
.progress-info {
flex: 1;
p {
margin: 0;
font-size: 15px;
font-weight: 600;
color: white;
&.small {
font-size: 11px;
color: rgba(255,255,255,0.6);
margin-top: 2px;
}
}
ion-progress-bar {
margin-top: 12px;
height: 6px;
border-radius: 3px;
}
}
}
.toolbar-section {
margin-bottom: 12px;
.toolbar-label {
font-size: 10px;
text-transform: uppercase;
letter-spacing: 1.5px;
color: rgba(255, 255, 255, 0.5);
margin-bottom: 6px;
padding-left: 4px;
font-weight: 700;
}
}
.horizontal-toolbar {
display: flex;
gap: 6px;
overflow-x: auto;
padding-bottom: 10px;
scrollbar-width: thin;
&::-webkit-scrollbar {
height: 3px;
}
&::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.15);
border-radius: 2px;
}
ion-button {
--border-radius: 10px;
margin: 0;
flex-shrink: 0;
font-size: 11px;
font-weight: 600;
}
}
.chords-toolbar {
ion-button {
--background: rgba(255, 255, 255, 0.1);
--color: #ffffff;
border: 1px solid rgba(255,255,255,0.1);
&:active {
--background: var(--ion-color-secondary);
}
}
}
.editor-wrapper {
margin-bottom: 20px;
background: #000000;
border-radius: 14px;
overflow: hidden;
border: 1px solid rgba(255,255,255,0.1);
box-shadow: inset 0 2px 10px rgba(0,0,0,0.5);
.editor-header {
background: rgba(255,255,255,0.05);
padding: 4px 8px 4px 16px;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid rgba(255,255,255,0.1);
.editor-title-group {
span {
font-size: 11px;
font-weight: 800;
color: var(--ion-color-secondary);
text-transform: uppercase;
letter-spacing: 0.5px;
}
}
.editor-actions {
display: flex;
gap: 0;
ion-button {
--color: rgba(255,255,255,0.6);
margin: 0;
height: 36px;
&[disabled] {
opacity: 0.3;
}
ion-icon {
font-size: 18px;
}
}
}
}
&.hc {
border: 2px solid #ffffff;
background: #000000;
.editor-header {
background: #ffffff;
span { color: #000000; }
small { color: #333; font-weight: 600; }
}
.content-textarea {
--color: #ffffff !important;
color: #ffffff !important;
background: #000000 !important;
font-size: 18px !important;
font-weight: 700 !important;
caret-color: #ff00ff;
}
}
}
.content-textarea {
font-family: 'Courier New', Courier, monospace;
font-size: 15px;
font-weight: 500;
color: #ffffff;
--padding-start: 16px;
--padding-end: 16px;
--padding-top: 16px;
--padding-bottom: 16px;
min-height: 400px;
}
.category-selectors {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
margin-bottom: 12px;
}
.select-item {
--background: rgba(255, 255, 255, 0.04);
--border-radius: 12px;
ion-select {
width: 100%;
--padding-start: 0;
color: white;
font-size: 14px;
}
}
.custom-input-item {
--background: rgba(255, 255, 255, 0.04);
--border-radius: 12px;
margin-bottom: 12px;
ion-label {
color: var(--ion-color-secondary) !important;
font-family: 'Outfit', sans-serif;
font-weight: 600;
margin-bottom: 6px !important;
font-size: 12px !important;
text-transform: uppercase;
}
ion-input {
color: white;
font-weight: 500;
}
}
.textarea-item {
--background: transparent;
--padding-start: 0;
--padding-end: 0;
}
.action-buttons {
margin-top: 24px;
margin-bottom: 50px;
}
.send-btn {
--border-radius: 16px;
--background: var(--ion-color-secondary);
font-weight: 700;
height: 60px;
font-size: 16px;
box-shadow: 0 8px 20px rgba(var(--ion-color-secondary-rgb), 0.3);
}
/* POPOVER STYLING */
.quick-popover {
--width: 90%;
--max-width: 400px;
--background: #1e1e1e;
--color: white;
.popover-container {
display: flex;
flex-direction: column;
gap: 16px;
padding: 16px;
}
.popover-section {
h6 {
margin: 0 0 8px 0;
font-size: 10px;
text-transform: uppercase;
color: var(--ion-color-medium);
letter-spacing: 1px;
}
}
.popover-grid {
display: grid;
gap: 4px;
ion-button {
margin: 0;
--padding-start: 4px;
--padding-end: 4px;
font-size: 12px;
height: 32px;
--background: rgba(255,255,255,0.08);
--color: white;
font-weight: 700;
}
}
.tags-grid {
grid-template-columns: repeat(2, 1fr);
}
.chords-grid {
grid-template-columns: repeat(4, 1fr);
}
}
@@ -0,0 +1,17 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ProposeCantoPage } from './propose-canto.page';
describe('ProposeCantoPage', () => {
let component: ProposeCantoPage;
let fixture: ComponentFixture<ProposeCantoPage>;
beforeEach(() => {
fixture = TestBed.createComponent(ProposeCantoPage);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -0,0 +1,254 @@
import { Component, OnInit, ViewChild, ElementRef, inject } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule, ToastController, IonTextarea, PopoverController, NavController } from '@ionic/angular';
import { createWorker } from 'tesseract.js';
import { CantiService } from '../../services/canti.service';
import { MyCantiService } from '../../services/my-canti.service';
@Component({
selector: 'app-propose-canto',
templateUrl: './propose-canto.page.html',
styleUrls: ['./propose-canto.page.scss'],
standalone: true,
imports: [CommonModule, FormsModule, IonicModule]
})
export class ProposeCantoPage implements OnInit {
@ViewChild('contentTextarea', { static: false }) contentTextarea!: IonTextarea;
@ViewChild('cameraInput', { static: false }) cameraInput!: ElementRef;
@ViewChild('docInput', { static: false }) docInput!: ElementRef;
public cantiService = inject(CantiService);
private myCantiService = inject(MyCantiService);
private navCtrl = inject(NavController);
title: string = '';
author: string = '';
youtubeLink: string = '';
selectedLiturgico: number[] = [];
selectedTematico: number[] = [];
private _content: string = '';
get content(): string { return this._content; }
set content(val: string) {
if (this._content !== val) {
this.saveToUndoStack(this._content);
this._content = val;
}
}
undoStack: string[] = [];
isProcessingOCR: boolean = false;
ocrProgress: number = 0;
isHighContrast: boolean = false;
commonChords = [
'DO', 'RE', 'MI', 'FA', 'SOL', 'LA', 'SI',
'DO-', 'RE-', 'MI-', 'FA-', 'SOL-', 'LA-', 'SI-',
'DO#', 'RE#', 'FA#', 'SOL#', 'LA#', 'DO#-', 'RE#-', 'FA#-', 'SOL#-', 'LA#-',
'DO7', 'RE7', 'MI7', 'FA7', 'SOL7', 'LA7', 'SI7', 'DO-7', 'RE-7', 'MI-7', 'LA-7', 'SI-7',
'DOmaj7', 'REmaj7', 'MImaj7', 'FAmaj7', 'SOLmaj7', 'LAmaj7', 'SImaj7',
'DO4', 'RE4', 'MI4', 'FA4', 'SOL4', 'LA4', 'SI4',
'DOdim', 'REdim', 'MIdim', 'FAdim', 'SOLdim', 'LAdim', 'SIdim',
'DOaug', 'REaug', 'MIaug', 'FAaug', 'SOLaug', 'LAaug', 'SIaug',
'DOm7', 'REm7', 'FAm7', 'SOLm7', 'LAm7'
];
commonTags = [
{ label: 'Ritornello', start: '{start_chorus}', end: '{end_chorus}' },
{ label: 'Strofa', start: '{start_verse}', end: '{end_verse}' },
{ label: 'Strofa Num.', start: '{start_verse_num}', end: '{end_verse_num}' },
{ label: 'Inciso', start: '{start_bridge}', end: '{end_bridge}' },
{ label: 'Intro Accordi', start: '{start_chord}', end: '{end_chord}' },
{ label: 'Commento', start: '{c: ', end: '}' },
{ label: 'ChordPro Strofa', start: '{sov}', end: '{eov}' },
{ label: 'ChordPro Rit.', start: '{soc}', end: '{eoc}' }
];
isChordPopoverOpen = false;
constructor(private toastController: ToastController, private popoverController: PopoverController) { }
ngOnInit() {
}
async insertText(tag: string) {
const input = await this.contentTextarea.getInputElement();
const start = input.selectionStart || 0;
const end = input.selectionEnd || 0;
this.content = this.content.substring(0, start) + tag + this.content.substring(end);
setTimeout(() => {
input.focus();
input.setSelectionRange(start + tag.length, start + tag.length);
}, 10);
}
insertChord(chord: string) {
this.insertText(`[${chord}]`);
}
undo() {
if (this.undoStack.length > 0) {
const previous = this.undoStack.pop();
if (previous !== undefined) {
this._content = previous;
}
}
}
private saveToUndoStack(val: string) {
if (this.undoStack.length >= 30) {
this.undoStack.shift();
}
this.undoStack.push(val);
}
takePhoto() {
this.cameraInput.nativeElement.click();
}
uploadDoc() {
this.docInput.nativeElement.click();
}
async onFileSelected(event: any, isCamera: boolean) {
const file = event.target.files[0];
if (!file) return;
this.isProcessingOCR = true;
this.ocrProgress = 0;
try {
const extension = file.name.split('.').pop().toLowerCase();
let extractedText = '';
if (extension === 'pdf') {
extractedText = await this.processPdf(file);
} else if (extension === 'docx') {
const mammoth = await import('mammoth');
const arrayBuffer = await file.arrayBuffer();
const result = await mammoth.extractRawText({ arrayBuffer });
extractedText = result.value;
} else if (['jpg', 'jpeg', 'png', 'webp'].includes(extension) || isCamera) {
extractedText = await this.processImageOCR(file);
} else {
extractedText = await file.text();
}
if (extractedText) {
const processed = this.smartProcessOCR(extractedText);
this.content += (this.content ? '\n\n' : '') + processed;
const toast = await this.toastController.create({
message: 'Documento elaborato!',
duration: 2000,
color: 'success'
});
toast.present();
}
} catch (error) {
console.error('File Processing Error:', error);
} finally {
this.isProcessingOCR = false;
this.ocrProgress = 0;
event.target.value = '';
}
}
async processImageOCR(file: File): Promise<string> {
const worker = await createWorker('ita', 1, {
logger: m => {
if (m.status === 'recognizing text') this.ocrProgress = m.progress;
}
});
const { data: { text } } = await worker.recognize(file);
await worker.terminate();
return text;
}
async processPdf(file: File): Promise<string> {
const pdfjsLib = await import('pdfjs-dist');
// Set worker src from CDN for PWA compatibility
pdfjsLib.GlobalWorkerOptions.workerSrc = `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjsLib.version}/pdf.worker.min.mjs`;
const arrayBuffer = await file.arrayBuffer();
const loadingTask = pdfjsLib.getDocument({ data: arrayBuffer });
const pdf = await loadingTask.promise;
let fullText = '';
for (let i = 1; i <= pdf.numPages; i++) {
const page = await pdf.getPage(i);
const textContent = await page.getTextContent();
const pageText = textContent.items.map((item: any) => item.str).join(' ');
fullText += pageText + '\n';
}
return fullText;
}
smartProcessOCR(text: string): string {
let lines = text.split('\n');
let processedLines: string[] = [];
const chordRegex = /\b(DO|RE|MI|FA|SOL|LA|SI|C|D|E|F|G|A|B)(#|b)?(m|-|min|maj|aug|dim)?(7|9|11|13)?\b/gi;
let inChorus = false;
let inVerse = false;
lines.forEach((line) => {
let trimmed = line.trim();
if (!trimmed) {
if (inChorus) { processedLines.push('{end_chorus}'); inChorus = false; }
if (inVerse) { processedLines.push('{end_verse}'); inVerse = false; }
processedLines.push('');
return;
}
const isChorusMarker = /^(Rit|Ritornello|Chorus|CORO)/i.test(trimmed);
if (isChorusMarker && !inChorus) {
if (inVerse) { processedLines.push('{end_verse}'); inVerse = false; }
processedLines.push('{start_chorus}');
inChorus = true;
if (trimmed.length > 12) processedLines.push(this.wrapChords(trimmed, chordRegex));
} else {
if (!inVerse && !inChorus && trimmed.length > 5) {
processedLines.push('{start_verse}');
inVerse = true;
}
processedLines.push(this.wrapChords(trimmed, chordRegex));
}
});
if (inChorus) processedLines.push('{end_chorus}');
if (inVerse) processedLines.push('{end_verse}');
return processedLines.join('\n');
}
private wrapChords(line: string, regex: RegExp): string {
const chordsInLine = line.match(regex);
if (chordsInLine && chordsInLine.length > 0) {
return line.replace(regex, (match) => `[${match.toUpperCase()}]`);
}
return line;
}
async openQuickMenu(event: any) {
this.isChordPopoverOpen = true;
}
async saveToMyCanti() {
if (!this.title || !this.content) return;
// Combine lit and tematico for id_momenti
const id_momenti = [...this.selectedLiturgico, ...this.selectedTematico];
await this.myCantiService.saveCanto({
titolo: this.title,
autore: this.author,
link_youtube: this.youtubeLink,
testo: this.content,
accordi: this.content, // Save to both fields for compatibility
id_momenti: id_momenti
});
this.navCtrl.back();
}
}
@@ -0,0 +1,16 @@
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SettingsPage } from './settings.page';
const routes: Routes = [
{
path: '',
component: SettingsPage
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule],
})
export class SettingsPageRoutingModule {}
+17
View File
@@ -0,0 +1,17 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { SettingsPageRoutingModule } from './settings-routing.module';
import { SettingsPage } from './settings.page';
@NgModule({
imports: [
CommonModule,
FormsModule,
IonicModule,
SettingsPageRoutingModule
],
declarations: [SettingsPage]
})
export class SettingsPageModule {}
+131
View File
@@ -0,0 +1,131 @@
<ion-header [translucent]="true" class="ion-no-border">
<ion-toolbar class="bg-gradient">
<ion-buttons slot="start">
<ion-back-button defaultHref="/home" color="secondary"></ion-back-button>
</ion-buttons>
<ion-title class="outfit-font">Impostazioni</ion-title>
</ion-toolbar>
</ion-header>
<ion-content [fullscreen]="true" class="bg-gradient">
<div class="settings-container ion-padding">
<div class="settings-group glass ion-margin-bottom">
<ion-item class="transparent-item" lines="none">
<ion-icon name="scan-outline" slot="start" color="secondary"></ion-icon>
<ion-label class="outfit-font">
<h2 class="settings-item-title">Schermo Intero Browser</h2>
<p class="settings-item-subtitle">Espande l'app a tutto schermo</p>
</ion-label>
<ion-toggle slot="end" [checked]="settingsService.browserFullscreen()" (ionChange)="settingsService.toggleBrowserFullscreen()" color="secondary"></ion-toggle>
</ion-item>
<ion-item class="transparent-item" lines="none">
<ion-icon name="expand-outline" slot="start" color="secondary"></ion-icon>
<ion-label class="outfit-font">
<h2 class="settings-item-title">Nascondi Barre (Player)</h2>
<p class="settings-item-subtitle">Modalità immersiva nel dettaglio canto</p>
</ion-label>
<ion-toggle slot="end" [checked]="settingsService.fullscreenMode()" (ionChange)="settingsService.toggleFullscreenMode()" color="secondary"></ion-toggle>
</ion-item>
<ion-item class="transparent-item" lines="none">
<ion-icon name="contrast-outline" slot="start" color="secondary"></ion-icon>
<ion-label class="outfit-font">
<h2 class="settings-item-title">Alto Contrasto</h2>
<p class="settings-item-subtitle">Colori più netti per il sole</p>
</ion-label>
<ion-toggle slot="end" [checked]="themeService.highContrast()" (ionChange)="themeService.toggleContrast()" color="secondary"></ion-toggle>
</ion-item>
<ion-item class="transparent-item" lines="none">
<ion-icon name="play-forward-outline" slot="start" color="secondary"></ion-icon>
<ion-label class="outfit-font">
<h2 class="settings-item-title">Avanzamento Automatico</h2>
<p class="settings-item-subtitle">Passa al canto successivo</p>
</ion-label>
<ion-toggle slot="end" [checked]="settingsService.autoAdvance()" (ionChange)="settingsService.toggleAutoAdvance()" color="secondary"></ion-toggle>
</ion-item>
<ion-item class="transparent-item" lines="none">
<ion-icon name="sunny-outline" slot="start" color="secondary"></ion-icon>
<ion-label class="outfit-font">
<h2 class="settings-item-title">Schermo Sempre Acceso</h2>
<p class="settings-item-subtitle">Evita che lo schermo si spenga</p>
</ion-label>
<ion-toggle slot="end" [checked]="settingsService.keepScreenOn()" (ionChange)="settingsService.toggleKeepScreenOn()" color="secondary"></ion-toggle>
</ion-item>
<ion-item class="transparent-item" lines="none">
<ion-icon name="create-outline" slot="start" color="secondary"></ion-icon>
<ion-label class="outfit-font">
<h2 class="settings-item-title">Editor e Canti Personali</h2>
<p class="settings-item-subtitle">Abilita aggiunta e gestione "Miei"</p>
</ion-label>
<ion-toggle slot="end" [checked]="settingsService.showEditor()" (ionChange)="settingsService.toggleEditor()" color="secondary"></ion-toggle>
</ion-item>
</div>
<!-- Display Mode Section -->
<div class="settings-group glass ion-margin-bottom">
<div class="group-header ion-padding-start ion-padding-top">
<h2 class="outfit-font settings-group-title">
Modalità Visualizzazione
</h2>
</div>
<div class="segment-wrapper ion-padding-horizontal ion-padding-bottom">
<div class="filter-buttons compact-mode ion-padding-horizontal ion-padding-bottom">
<div class="filter-btn glass"
[class.active-btn]="!settingsService.showChordsDefault()"
(click)="onModeChange({detail: {value: 'text'}})">
<span>Solo Testo</span>
</div>
<div class="filter-btn glass"
[class.active-btn]="settingsService.showChordsDefault()"
(click)="onModeChange({detail: {value: 'chords'}})">
<span>Accordi</span>
</div>
</div>
</div>
</div>
<div class="settings-group glass ion-margin-top" *ngIf="settingsService.showEditor()">
<ion-item class="transparent-item" lines="none" (click)="myCantiService.sendAllMyCanti()" detail="true" button *ngIf="myCantiService.myCanti().length > 0">
<ion-icon name="send-outline" slot="start" color="secondary"></ion-icon>
<ion-label class="outfit-font">
<h2 class="settings-item-title">Proponi i miei canti ({{ myCantiService.myCanti().length }})</h2>
<p class="settings-item-subtitle">Invia a frassidavid@gmail.com</p>
</ion-label>
</ion-item>
</div>
<div class="settings-group glass ion-margin-top">
<ion-item class="transparent-item" lines="none" (click)="fullRefresh()" detail="true" button>
<ion-icon name="cloud-download-outline" slot="start" color="secondary"></ion-icon>
<ion-label class="outfit-font">
<h2 class="settings-item-title">Allinea con Server</h2>
<p class="settings-item-subtitle">Aggiorna canti e versione app</p>
</ion-label>
<ion-spinner slot="end" name="crescent" color="secondary" *ngIf="cantiService.loading()"></ion-spinner>
</ion-item>
<div class="sync-info ion-padding-bottom">
<p class="outfit-font settings-item-subtitle">
Versione: <strong>v{{ version }}</strong> &bull;
Canti: <strong>{{ cantiService.canti().length }}</strong>
</p>
</div>
<div class="sync-progress" *ngIf="cantiService.loading()">
<div class="progress-bar" [style.width.%]="cantiService.progress()"></div>
</div>
</div>
<div class="credits-footer ion-padding-top ion-text-center">
<p class="outfit-font email-text">
info@canticristiani.it
</p>
</div>
<div class="ion-padding-top ion-text-center">
<p class="outfit-font settings-footer-text">
Le preferenze vengono salvate automaticamente.
</p>
</div>
</div>
</ion-content>
+178
View File
@@ -0,0 +1,178 @@
.bg-gradient {
--background: radial-gradient(circle at top left, #2d3436 0%, #121212 100%);
background: radial-gradient(circle at top left, #2d3436 0%, #121212 100%);
}
.outfit-font {
font-family: 'Outfit', sans-serif;
}
.settings-container {
max-width: 600px;
margin: 0 auto;
}
.settings-group {
border-radius: 20px;
overflow: hidden;
border: 1px solid rgba(255, 255, 255, 0.1);
}
.transparent-item {
--background: transparent;
--color: white;
--padding-start: 16px;
--inner-padding-end: 16px;
}
.settings-item-title {
color: white;
font-weight: 600;
margin: 0;
}
.settings-item-subtitle {
color: rgba(255, 255, 255, 0.6);
margin: 0;
}
.settings-group-title {
font-size: 1.1rem;
font-weight: 700;
color: var(--ion-color-secondary);
margin: 0;
}
.sub-group-title {
font-size: 0.75rem;
font-weight: 700;
color: rgba(255, 255, 255, 0.4);
text-transform: uppercase;
letter-spacing: 0.05em;
margin-bottom: 4px;
}
.playlist-item {
--min-height: 44px;
background: rgba(255, 255, 255, 0.03) !important;
margin: 4px 8px;
border-radius: 8px;
.settings-item-title {
font-size: 0.9rem;
}
}
ion-radio {
--color: rgba(255, 255, 255, 0.4);
--color-checked: var(--ion-color-secondary);
font-size: 1rem;
width: 100%;
ion-label {
color: white;
}
}
.compact-mode {
.filter-btn {
flex: 1;
justify-content: center;
}
}
.group-header {
margin-bottom: 8px;
}
.sync-info {
margin-top: 4px;
padding-left: 56px;
p {
font-size: 0.75rem;
color: rgba(255, 255, 255, 0.4);
strong {
color: var(--ion-color-secondary);
}
}
}
.sync-progress {
height: 4px;
background: rgba(255, 255, 255, 0.1);
width: 100%;
.progress-bar {
height: 100%;
background: var(--ion-color-secondary);
transition: width 0.3s ease;
}
}
.settings-footer-text {
color: rgba(255, 255, 255, 0.3);
font-size: 0.8rem;
}
// High contrast overrides
:host-context(body.high-contrast) {
.settings-item-title {
color: black !important;
}
.settings-item-subtitle {
color: rgba(0, 0, 0, 0.6) !important;
}
.settings-footer-text {
color: rgba(0, 0, 0, 0.4) !important;
}
.sub-group-title {
color: rgba(0, 0, 0, 0.7) !important;
}
.sync-info p {
color: rgba(0, 0, 0, 0.7) !important;
}
ion-label {
color: black !important;
}
ion-radio {
--color: rgba(0, 0, 0, 0.3);
color: black !important;
ion-label {
color: black !important;
}
}
}
.credits-footer {
margin-top: 24px;
border-top: 1px solid rgba(255, 255, 255, 0.1);
padding-top: 24px;
.credits-text {
font-size: 1rem;
font-weight: 600;
color: var(--ion-color-secondary);
line-height: 1.6;
}
.email-text {
font-size: 0.9rem;
color: rgba(255, 255, 255, 0.5);
margin-top: 8px;
}
}
:host-context(body.high-contrast) {
.credits-footer {
border-top-color: rgba(0, 0, 0, 0.2);
.credits-text {
color: black !important;
}
.email-text {
color: rgba(0, 0, 0, 0.6) !important;
}
}
}
+75
View File
@@ -0,0 +1,75 @@
import { Component, inject } from '@angular/core';
import { ThemeService } from '../../services/theme.service';
import { SettingsService } from '../../services/settings.service';
import { CantiService } from '../../services/canti.service';
import { ConnectivityService } from '../../services/connectivity.service';
import { SwUpdate } from '@angular/service-worker';
import { ToastController, ModalController, AlertController } from '@ionic/angular';
import { VERSION } from '../../version';
import { PlaylistService } from '../../services/playlist.service';
import { Router } from '@angular/router';
import { MyCantiService } from '../../services/my-canti.service';
@Component({
selector: 'app-settings',
templateUrl: './settings.page.html',
styleUrls: ['./settings.page.scss'],
standalone: false
})
export class SettingsPage {
public myCantiService = inject(MyCantiService);
public themeService = inject(ThemeService);
public settingsService = inject(SettingsService);
public cantiService = inject(CantiService);
public connectivityService = inject(ConnectivityService);
public playlistService = inject(PlaylistService);
private swUpdate = inject(SwUpdate);
private toastCtrl = inject(ToastController);
private modalCtrl = inject(ModalController);
private alertCtrl = inject(AlertController);
private router = inject(Router);
public version = VERSION;
constructor() {}
onModeChange(event: any) {
this.settingsService.setShowChordsDefault(event.detail.value === 'chords');
}
async fullRefresh() {
// 1. Refresh JSON data
this.cantiService.refresh();
// 2. Check for Service Worker updates
if (this.swUpdate.isEnabled) {
try {
const updateFound = await this.swUpdate.checkForUpdate();
if (updateFound) {
const toast = await this.toastCtrl.create({
message: 'Nuova versione disponibile! Aggiornamento in corso...',
duration: 2000,
color: 'secondary'
});
await toast.present();
setTimeout(() => {
window.location.reload();
}, 2000);
return;
}
} catch (err) {
console.error('Failed to check for updates', err);
}
}
const toast = await this.toastCtrl.create({
message: 'Dati aggiornati correttamente!',
duration: 2000,
color: 'success'
});
await toast.present();
}
}
+187
View File
@@ -0,0 +1,187 @@
import { Injectable, signal } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AudioEngineService {
public isListening = signal<boolean>(false);
public wordsDetected = signal<number>(0);
public linesDetected = signal<number>(0);
public energyLevel = signal<number>(0); // For visual feedback
public searchTranscript = signal<string>('');
public isSearching = signal<boolean>(false);
public sensitivity = signal<number>(75); // Default sensitivity (50-100)
public clearSearchTranscript() {
this.searchTranscript.set('');
}
private audioContext: AudioContext | null = null;
private analyser: AnalyserNode | null = null;
private stream: MediaStream | null = null;
private animationFrame: number | null = null;
private recognition: any = null;
// Detection logic state
private isSpeaking: boolean = false;
private lastSilenceTime: number = Date.now();
private lastWordTime: number = 0;
// Constants for tuning - Optimized for close proximity (singer/guitarist)
private readonly SILENCE_GAP = 100; // ms
private readonly LINE_SILENCE_GAP = 600; // ms
private readonly COOLDOWN = 1000; // ms
private peakEnergy: number = 0;
private lineStarted: boolean = false;
constructor() {
this.initSpeechRecognition();
}
private initSpeechRecognition() {
const SpeechRecognition = (window as any).SpeechRecognition || (window as any).webkitSpeechRecognition;
if (SpeechRecognition) {
this.recognition = new SpeechRecognition();
this.recognition.continuous = false; // Stop after one phrase for search
this.recognition.interimResults = true;
this.recognition.lang = 'it-IT';
this.recognition.onresult = (event: any) => {
const text = event.results[0][0].transcript;
this.searchTranscript.set(text);
};
this.recognition.onend = () => {
this.isSearching.set(false);
};
this.recognition.onerror = (err: any) => {
console.error('Search recognition error:', err);
this.isSearching.set(false);
};
}
}
startSearchRecognition() {
if (!this.recognition) {
alert('Il riconoscimento vocale non è supportato in questo browser.');
return;
}
this.searchTranscript.set('');
this.isSearching.set(true);
try {
this.recognition.start();
} catch (e) {
console.warn('Recognition already started', e);
}
}
stopSearchRecognition() {
this.recognition?.stop();
this.isSearching.set(false);
}
async startListening() {
if (this.isListening()) return;
try {
this.stream = await navigator.mediaDevices.getUserMedia({
audio: {
echoCancellation: true,
noiseSuppression: true,
autoGainControl: false // Prevents boosting background noise during silence
}
});
this.audioContext = new AudioContext();
const source = this.audioContext.createMediaStreamSource(this.stream);
this.analyser = this.audioContext.createAnalyser();
this.analyser.fftSize = 512;
source.connect(this.analyser);
this.isListening.set(true);
this.processAudio();
} catch (err) {
console.error('Error accessing microphone', err);
alert('Errore microfono: assicurati di usare HTTPS e di aver dato i permessi.');
}
}
stopListening() {
if (this.animationFrame) cancelAnimationFrame(this.animationFrame);
this.stream?.getTracks().forEach(track => track.stop());
this.audioContext?.close();
this.isListening.set(false);
this.energyLevel.set(0);
}
private processAudio() {
if (!this.analyser) return;
const bufferLength = this.analyser.frequencyBinCount;
const dataArray = new Uint8Array(bufferLength);
const analyze = () => {
this.analyser!.getByteFrequencyData(dataArray);
// Calculate average energy (volume)
let sum = 0;
for (let i = 0; i < bufferLength; i++) {
sum += dataArray[i];
}
const avgEnergy = sum / bufferLength;
this.energyLevel.set(avgEnergy);
const now = Date.now();
// Balanced mapping: 0% -> 220 (very quiet), 100% -> 20 (very sensitive)
const currentThreshold = 220 - (this.sensitivity() * 2.0);
if (avgEnergy > currentThreshold) {
if (avgEnergy > this.peakEnergy) {
this.peakEnergy = avgEnergy;
}
if (!this.isSpeaking) {
this.isSpeaking = true;
this.peakEnergy = avgEnergy;
this.lastSilenceTime = now;
}
// Se siamo in "speaking" e sentiamo un calo significativo rispetto al picco recente (almeno 30% di calo)
// Questo permette di avanzare anche se c'è rumore di fondo sopra la soglia base.
const dropRatio = (this.peakEnergy - avgEnergy) / this.peakEnergy;
if (this.isSpeaking && dropRatio > 0.35 && this.peakEnergy > currentThreshold * 1.2) {
if (now - this.lastWordTime > this.COOLDOWN) {
this.linesDetected.update(v => v + 1);
this.lastWordTime = now;
this.peakEnergy = avgEnergy; // Reset peak
this.isSpeaking = false;
console.log('Line advanced - relative drop detected', { dropRatio, avgEnergy, peak: this.peakEnergy });
}
}
this.lastSilenceTime = now;
} else {
// Sotto soglia (silenzio per il sistema)
if (this.isSpeaking && (now - this.lastSilenceTime > 200)) {
if (now - this.lastWordTime > this.COOLDOWN) {
this.linesDetected.update(v => v + 1);
this.lastWordTime = now;
console.log('Line advanced - silence detected');
}
this.isSpeaking = false;
this.peakEnergy = 0;
}
}
this.animationFrame = requestAnimationFrame(analyze);
};
analyze();
}
resetWordCount() {
this.wordsDetected.set(0);
this.linesDetected.set(0);
this.lineStarted = false;
}
}
+150
View File
@@ -0,0 +1,150 @@
import { Injectable, signal, inject } from '@angular/core';
import { HttpClient, HttpEventType } from '@angular/common/http';
import { Storage } from '@ionic/storage-angular';
export interface Canto {
id: string;
id_canti: number;
titolo: string;
testo: string;
accordi?: string;
autore?: string;
link_youtube?: string;
id_momenti?: number[];
}
export interface Indice {
id: number;
tag_name: string;
slug: string;
type: 'liturgico' | 'tematico';
}
@Injectable({
providedIn: 'root'
})
export class CantiService {
private http = inject(HttpClient);
private storage = inject(Storage);
private _storage: Storage | null = null;
public canti = signal<Canto[]>([]);
public indiceLiturgico = signal<Indice[]>([]);
public indiceTematico = signal<Indice[]>([]);
// Keep momenti for backward compatibility or temporary usage
public momenti = signal<Indice[]>([]);
public loading = signal<boolean>(false);
public progress = signal<number>(0);
private API_URL = 'https://www.canticristiani.it/api/canti.json';
constructor() {
this.init();
}
async init() {
const storage = await this.storage.create();
this._storage = storage;
await this.loadFromStorage();
this.refresh();
}
async loadFromStorage() {
const cachedCanti = await this._storage?.get('canti');
const cachedLit = await this._storage?.get('indiceLiturgico');
const cachedTem = await this._storage?.get('indiceTematico');
if (cachedCanti) this.canti.set(cachedCanti);
if (cachedLit) this.indiceLiturgico.set(cachedLit);
if (cachedTem) this.indiceTematico.set(cachedTem);
// Sync momenti
if (cachedLit) this.momenti.set(cachedLit);
}
refresh() {
this.loading.set(true);
this.progress.set(0);
this.http.get(`${this.API_URL}?t=${Date.now()}`, {
reportProgress: true,
observe: 'events'
}).subscribe({
next: async (event: any) => {
if (event.type === HttpEventType.DownloadProgress) {
if (event.total) {
this.progress.set(Math.round((event.loaded / event.total) * 100));
} else {
this.progress.update(p => p < 90 ? p + 5 : p);
}
} else if (event.type === HttpEventType.Response) {
const response = event.body;
if (response?.canti?.data) {
const cantiData = response.canti.data;
const litData = (response.indice_liturgico?.data || []).map((x: any) => ({
id: x.id_indice_liturgico,
tag_name: x.tag_name,
slug: x.slug,
type: 'liturgico'
}));
const temData = (response.indice_tematico?.data || []).map((x: any) => ({
id: x.id_indice_tematico,
tag_name: x.tag_name,
slug: x.slug,
type: 'tematico'
}));
const pivotData = response.tema?.data || [];
// Optimize linking: O(N+M) instead of O(N*M)
const pivotMap = new Map<number, number[]>();
pivotData.forEach((p: any) => {
if (!pivotMap.has(p.id_canti)) pivotMap.set(p.id_canti, []);
pivotMap.get(p.id_canti)!.push(p.id_momento);
});
const linkedCanti = cantiData.map((c: any) => ({
...c,
id: c.id_canti.toString(),
id_momenti: pivotMap.get(c.id_canti) || []
}));
this.canti.set(linkedCanti);
this.indiceLiturgico.set(litData);
this.indiceTematico.set(temData);
this.momenti.set(litData); // Fallback
await this._storage?.set('canti', linkedCanti);
await this._storage?.set('indiceLiturgico', litData);
await this._storage?.set('indiceTematico', temData);
}
this.progress.set(100);
this.loading.set(false);
}
},
error: (error) => {
console.error('Failed to fetch canti', error);
this.loading.set(false);
}
});
}
getCantoById(id: string) {
return this.canti().find(c => c.id === id);
}
getYoutubeId(urlOrId: string | undefined): string | null {
if (!urlOrId) return null;
if (urlOrId.length === 11) return urlOrId;
const regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;
const match = urlOrId.match(regExp);
return (match && match[7].length === 11) ? match[7] : null;
}
getYoutubeThumb(urlOrId: string | undefined): string | null {
const id = this.getYoutubeId(urlOrId);
return id ? `https://img.youtube.com/vi/${id}/mqdefault.jpg` : null;
}
getStorage() {
return this._storage;
}
}
+13
View File
@@ -0,0 +1,13 @@
import { Injectable, signal } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ConnectivityService {
public isOnline = signal<boolean>(navigator.onLine);
constructor() {
window.addEventListener('online', () => this.isOnline.set(true));
window.addEventListener('offline', () => this.isOnline.set(false));
}
}
+237
View File
@@ -0,0 +1,237 @@
import { Injectable } from '@angular/core';
export interface ChordSegment {
text: string;
chord?: string;
}
export interface ParsedLine {
segments: ChordSegment[];
text: string;
}
export interface ParsedSection {
type: 'verse' | 'chorus' | 'verse_num';
lines: ParsedLine[];
verseNumber?: number;
}
@Injectable({
providedIn: 'root'
})
export class LyricsParserService {
/**
* Parse plain text (campo 'testo') into structured sections.
*/
parseText(raw: string): ParsedSection[] {
if (!raw) return [];
return this.parseSections(raw, false);
}
/**
* Parse text with inline chords (campo 'accordi') into structured sections.
*/
parseAccordi(raw: string): ParsedSection[] {
if (!raw) return [];
return this.parseSections(raw, true);
}
private parseSections(raw: string, withChords: boolean): ParsedSection[] {
const sections: ParsedSection[] = [];
let currentType: 'verse' | 'chorus' | 'verse_num' = 'verse';
let currentLines: ParsedLine[] = [];
let verseNumCounter = 0;
const lines = raw.split('\n');
for (const line of lines) {
const trimmed = line.trim();
// Detect section start tags
if (trimmed === '{start_verse}' || trimmed === '{sov}') {
this.pushSection(sections, currentType, currentLines);
currentType = 'verse';
currentLines = [];
continue;
}
if (trimmed === '{start_chorus}' || trimmed === '{soc}') {
this.pushSection(sections, currentType, currentLines);
currentType = 'chorus';
currentLines = [];
continue;
}
if (trimmed === '{start_verse_num}') {
this.pushSection(sections, currentType, currentLines);
currentType = 'verse_num';
verseNumCounter++;
currentLines = [];
continue;
}
// Detect section end tags — just skip them
if (trimmed === '{end_verse}' || trimmed === '{eov}' || trimmed === '{end_chorus}' || trimmed === '{eoc}' || trimmed === '{end_verse_num}') {
this.pushSection(sections, currentType, currentLines, currentType === 'verse_num' ? verseNumCounter : undefined);
currentLines = [];
continue;
}
// Skip structural tags (already handled above)
if (trimmed.startsWith('{') && trimmed.endsWith('}')) {
continue;
}
// Skip empty lines
if (trimmed.length === 0) {
continue;
}
// Parse line
if (withChords) {
currentLines.push(this.parseChordLine(line));
} else {
// CLEAN CHORDS in text-only mode: remove [anything]
const cleanLine = line.replace(/\[[^\]]*\]/g, '').trim();
if (cleanLine.length > 0) {
currentLines.push({
text: cleanLine,
segments: [{ text: cleanLine }]
});
}
}
}
// Push any remaining lines
this.pushSection(sections, currentType, currentLines);
return sections;
}
private pushSection(sections: ParsedSection[], type: 'verse' | 'chorus' | 'verse_num', lines: ParsedLine[], verseNumber?: number): void {
if (lines.length > 0) {
sections.push({ type, lines, verseNumber });
}
}
/**
* Parse a single line containing inline chord tags.
* Format: "[RE]Tu sei Re[LA]" → segments with chords positioned above text
*
* The chord tag appears BEFORE the text it belongs to:
* [RE]Tu sei Re → chord "RE" above "Tu sei Re"
*
* But a chord can also appear at the END of text:
* sei Re Gesù[SOL] → text "sei Re Gesù" then chord "SOL" with empty text
*/
parseChordLine(line: string): ParsedLine {
const segments: ChordSegment[] = [];
// Clean up non-breaking spaces
const cleaned = line.replace(/\u00a0/g, ' ').trim();
// Regex to match [CHORD] tags and text between them
const chordRegex = /\[([^\]]+)\]/g;
let lastIndex = 0;
let match: RegExpExecArray | null;
while ((match = chordRegex.exec(cleaned)) !== null) {
// Text before this chord tag
const textBefore = cleaned.substring(lastIndex, match.index);
if (textBefore.length > 0) {
// This text has no chord above it (or belongs to previous chord)
if (segments.length > 0 && segments[segments.length - 1].text === '') {
// Previous segment had a chord but no text — attach this text to it
segments[segments.length - 1].text = textBefore;
} else {
segments.push({ text: textBefore });
}
}
// Add the chord as a new segment (text will be filled by next text chunk)
segments.push({ chord: match[1], text: '' });
lastIndex = match.index + match[0].length;
}
// Remaining text after the last chord
const remaining = cleaned.substring(lastIndex);
if (remaining.length > 0) {
if (segments.length > 0 && segments[segments.length - 1].text === '') {
segments[segments.length - 1].text = remaining;
} else {
segments.push({ text: remaining });
}
}
// If no chords found, just return plain text
if (segments.length === 0) {
segments.push({ text: cleaned });
}
// Build plain text
const plainText = segments.map(s => s.text).join('');
return { segments, text: plainText };
}
private readonly scale = ['DO', 'DO#', 'RE', 'RE#', 'MI', 'FA', 'FA#', 'SOL', 'SOL#', 'LA', 'LA#', 'SI'];
private readonly flatScale = ['DO', 'REb', 'RE', 'MIb', 'MI', 'FA', 'SOLb', 'SOL', 'LAb', 'LA', 'SIb', 'SI'];
/**
* Transpose a single chord by a given number of semitones.
* Handles Italian notation.
*/
transposeChord(chord: string, semitones: number): string {
if (!chord || semitones === 0) return chord;
// Handle slash chords (e.g., DO/SOL)
if (chord.includes('/')) {
return chord.split('/')
.map(part => this.transposeChord(part.trim(), semitones))
.join('/');
}
const possibleRoots = [...this.scale, ...this.flatScale].sort((a, b) => b.length - a.length);
let root = '';
let suffix = '';
for (const r of possibleRoots) {
if (chord.startsWith(r)) {
root = r;
suffix = chord.substring(r.length);
break;
}
}
if (!root) return chord;
let index = this.scale.indexOf(root);
if (index === -1) index = this.flatScale.indexOf(root);
if (index === -1) return chord;
let newIndex = (index + semitones) % 12;
if (newIndex < 0) newIndex += 12;
// Preserve the original notation style (sharp or flat) if possible
const useFlat = this.flatScale.includes(root);
const newRoot = useFlat ? this.flatScale[newIndex] : this.scale[newIndex];
return newRoot + suffix;
}
/**
* Transpose all chords in a parsed structure.
*/
transposeSections(sections: ParsedSection[], semitones: number): ParsedSection[] {
if (semitones === 0) return sections;
return sections.map(section => ({
...section,
lines: section.lines.map(line => ({
...line,
segments: line.segments.map(segment => ({
...segment,
chord: segment.chord ? this.transposeChord(segment.chord, semitones) : undefined
}))
}))
}));
}
}
+80
View File
@@ -0,0 +1,80 @@
import { Injectable, inject } from '@angular/core';
import { CantiService } from './canti.service';
import { MyCantiService } from './my-canti.service';
@Injectable({
providedIn: 'root'
})
export class MediaSessionService {
private cantiService = inject(CantiService);
private myCantiService = inject(MyCantiService);
public updateMetadata(cantoId: string) {
if (!('mediaSession' in navigator)) return;
let canto = this.cantiService.getCantoById(cantoId);
if (!canto) {
canto = this.myCantiService.myCanti().find(c => c.id === cantoId);
}
if (!canto) return;
const thumb = this.cantiService.getYoutubeThumb(canto.link_youtube) || 'assets/icons/icon-512x512.png';
if (!('MediaMetadata' in window)) return;
try {
(navigator as any).mediaSession.metadata = new (window as any).MediaMetadata({
title: canto.titolo,
artist: canto.autore || 'Canti Cristiani',
album: 'Canti Cristiani',
artwork: [
{ src: thumb, sizes: '96x96', type: 'image/jpeg' },
{ src: thumb, sizes: '128x128', type: 'image/jpeg' },
{ src: thumb, sizes: '192x192', type: 'image/jpeg' },
{ src: thumb, sizes: '256x256', type: 'image/jpeg' },
{ src: thumb, sizes: '384x384', type: 'image/jpeg' },
{ src: thumb, sizes: '512x512', type: 'image/jpeg' },
]
});
} catch (e) {
console.error('Error updating Media Session metadata', e);
}
}
public setPlaybackState(state: 'playing' | 'paused' | 'none') {
if (!('mediaSession' in navigator)) return;
(navigator as any).mediaSession.playbackState = state;
}
public initActionHandlers(callbacks: {
play: () => void,
pause: () => void,
next?: () => void,
prev?: () => void,
seekto?: (time: number) => void
}) {
if (!('mediaSession' in navigator)) return;
const ms = (navigator as any).mediaSession;
ms.setActionHandler('play', callbacks.play);
ms.setActionHandler('pause', callbacks.pause);
if (callbacks.next) {
ms.setActionHandler('nexttrack', callbacks.next);
}
if (callbacks.prev) {
ms.setActionHandler('previoustrack', callbacks.prev);
}
try {
if (callbacks.seekto) {
ms.setActionHandler('seekto', (details: any) => {
if (details.seekTime !== undefined && callbacks.seekto) {
callbacks.seekto(details.seekTime);
}
});
}
} catch (e) {}
}
}
+84
View File
@@ -0,0 +1,84 @@
import { Injectable, signal, inject } from '@angular/core';
import { Storage } from '@ionic/storage-angular';
import { Canto, CantiService } from './canti.service';
import { ToastController } from '@ionic/angular';
@Injectable({
providedIn: 'root'
})
export class MyCantiService {
private storage = inject(Storage);
private cantiService = inject(CantiService);
private toastController = inject(ToastController);
private _storage: Storage | null = null;
public myCanti = signal<Canto[]>([]);
constructor() {
this.init();
}
async init() {
this._storage = this.cantiService.getStorage();
if (!this._storage) {
// If CantiService hasn't initialized storage yet, wait a bit
setTimeout(() => this.init(), 500);
return;
}
const saved = await this._storage.get('my-canti');
if (saved) {
this.myCanti.set(saved);
}
}
async saveCanto(canto: Partial<Canto>) {
const current = this.myCanti();
const newCanto: Canto = {
id: `my_${Date.now()}`,
id_canti: Date.now(), // Fake ID for internal logic
titolo: canto.titolo || 'Senza Titolo',
testo: canto.testo || '',
accordi: canto.accordi,
autore: canto.autore,
link_youtube: canto.link_youtube,
id_momenti: canto.id_momenti || []
};
const updated = [...current, newCanto];
this.myCanti.set(updated);
await this._storage?.set('my-canti', updated);
const toast = await this.toastController.create({
message: 'Canto salvato nei "Miei Canti"!',
duration: 2000,
color: 'success'
});
toast.present();
}
async deleteCanto(id: string) {
const updated = this.myCanti().filter(c => c.id !== id);
this.myCanti.set(updated);
await this._storage?.set('my-canti', updated);
}
async sendAllMyCanti() {
const data = {
version: new Date().toISOString(),
canti: this.myCanti()
};
const body = JSON.stringify(data, null, 2);
const subject = `Proposta Collection Canti: ${this.myCanti().length} brani`;
const mailtoUrl = `mailto:frassidavid@gmail.com?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;
window.location.href = mailtoUrl;
const toast = await this.toastController.create({
message: 'Email generata con il JSON dei tuoi canti.',
duration: 3000,
color: 'secondary'
});
toast.present();
}
}
+16
View File
@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { MyCanti } from './my-canti';
describe('MyCanti', () => {
let service: MyCanti;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(MyCanti);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
+168
View File
@@ -0,0 +1,168 @@
import { Injectable, signal, inject } from '@angular/core';
import { Storage } from '@ionic/storage-angular';
import { Canto, CantiService } from './canti.service';
import * as QRCode from 'qrcode';
@Injectable({
providedIn: 'root'
})
export class PlaylistService {
private storage = inject(Storage);
private cantiService = inject(CantiService);
public selectionMode = signal<boolean>(false);
public selectedIds = signal<Set<string>>(new Set());
public playlists = signal<any[]>([]);
public lastPlaylist = signal<any | null>(null);
public autoPlayPlaylist = signal<boolean>(false);
public activeListIds = signal<string[]>([]);
public activeListName = signal<string | null>(null);
public activePlaylistId = signal<string | null>(null);
private _storage: Storage | null = null;
constructor() {
this.init();
}
async init() {
const storage = await this.storage.create();
this._storage = storage;
const saved = await this._storage.get('playlists');
if (saved) {
this.playlists.set(saved);
}
const last = await this._storage?.get('lastPlaylist');
if (last) {
this.lastPlaylist.set(last);
}
}
toggleSelectionMode() {
this.selectionMode.update(v => !v);
if (!this.selectionMode()) {
this.selectedIds.set(new Set());
}
}
toggleSongSelection(id: string) {
if (!this.selectionMode()) {
const active = this.activeListIds();
if (active.length > 0) {
this.selectedIds.set(new Set(active));
}
this.selectionMode.set(true);
}
this.selectedIds.update(set => {
const newSet = new Set(set);
if (newSet.has(id)) {
newSet.delete(id);
} else {
newSet.add(id);
}
return newSet;
});
}
async savePlaylist(name: string, ids: string[]) {
const editId = this.activePlaylistId();
let newPlaylist: any;
if (editId) {
this.playlists.update(p => p.map(pl => {
if (pl.id === editId) {
return { ...pl, name, ids };
}
return pl;
}));
newPlaylist = this.playlists().find(pl => pl.id === editId);
} else {
newPlaylist = {
id: Date.now().toString(),
name,
ids,
createdAt: new Date()
};
this.playlists.update(p => [newPlaylist, ...p]);
}
this.lastPlaylist.set(newPlaylist);
this.activeListIds.set(ids);
this.activeListName.set(name);
await this._storage?.set('playlists', this.playlists());
await this._storage?.set('lastPlaylist', newPlaylist);
// Reset selection mode, IDs and editing state after saving
this.selectedIds.set(new Set());
this.selectionMode.set(false);
this.activePlaylistId.set(newPlaylist.id);
}
async deletePlaylist(id: string) {
this.playlists.update(p => p.filter(pl => pl.id !== id));
await this._storage?.set('playlists', this.playlists());
}
async generateQR(ids: string[], name: string): Promise<string> {
const data = this.getShareLink(ids, name);
return await QRCode.toDataURL(data, {
width: 400,
margin: 2,
color: {
dark: '#2d3436',
light: '#ffffff'
}
});
}
getShareLink(ids: string[], name: string): string {
const data = JSON.stringify({ name, ids });
// Use btoa safely for UTF-8 strings
const base64 = btoa(unescape(encodeURIComponent(data)));
// Always use the production URL for sharing links as requested
const productionUrl = 'https://www.canticristiani.it/ionic';
return `${productionUrl}/?import=${base64}`;
}
processImportJson(json: any): boolean {
if (json && json.name && json.ids) {
this.activeListIds.set(json.ids);
this.activeListName.set(json.name);
return true;
}
return false;
}
async sharePlaylistQR(ids: string[], name: string) {
const qrImage = await this.generateQR(ids, name);
const shareLink = this.getShareLink(ids, name);
const fileName = `${name.toLowerCase().replace(/\s+/g, '_')}_qr.png`;
try {
const res = await fetch(qrImage);
const blob = await res.blob();
const file = new File([blob], fileName, { type: 'image/png' });
if (navigator.share && navigator.canShare && navigator.canShare({ files: [file] })) {
await navigator.share({
files: [file],
title: 'Playlist CantiCristiani',
text: `Ecco la playlist: ${name}\n\nClicca qui per aprirla subito: ${shareLink}`
});
} else {
// Fallback: download
const link = document.createElement('a');
link.href = qrImage;
link.download = fileName;
link.click();
}
} catch (err) {
console.error('Share failed', err);
}
}
async loadPlaylists() {
}
}
+138
View File
@@ -0,0 +1,138 @@
import { Injectable, signal, effect } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class SettingsService {
/** Default mode for viewing songs: true = chords, false = text only */
public showChordsDefault = signal<boolean>(false);
/** UI Fullscreen mode (lyrics only): true = active */
public fullscreenMode = signal<boolean>(false);
/** Browser Fullscreen state: true = fullscreen active */
public browserFullscreen = signal<boolean>(!!document.fullscreenElement);
/** Avanzamento automatico: true = passa al brano successivo automaticamente */
public autoAdvance = signal<boolean>(true);
/** Editor e Canti Personali: true = mostra funzioni aggiunta e lista "Miei" */
public showEditor = signal<boolean>(false);
/** Schermo sempre acceso: true = attiva Screen Wake Lock */
public keepScreenOn = signal<boolean>(false);
private wakeLock: any = null;
constructor() {
const savedChords = localStorage.getItem('show-chords-default');
if (savedChords !== null) {
this.showChordsDefault.set(savedChords === 'true');
}
const savedFullscreen = localStorage.getItem('fullscreen-mode');
if (savedFullscreen !== null) {
this.fullscreenMode.set(savedFullscreen === 'true');
}
const savedEditor = localStorage.getItem('show-editor');
if (savedEditor !== null) {
this.showEditor.set(savedEditor === 'true');
}
const savedAutoAdvance = localStorage.getItem('auto-advance');
if (savedAutoAdvance !== null) {
this.autoAdvance.set(savedAutoAdvance === 'true');
}
const savedKeepScreenOn = localStorage.getItem('keep-screen-on');
if (savedKeepScreenOn !== null) {
this.keepScreenOn.set(savedKeepScreenOn === 'true');
}
// Sync browser fullscreen state with listeners
document.addEventListener('fullscreenchange', () => {
this.browserFullscreen.set(!!document.fullscreenElement);
});
effect(() => {
localStorage.setItem('show-chords-default', this.showChordsDefault().toString());
});
effect(() => {
localStorage.setItem('fullscreen-mode', this.fullscreenMode().toString());
});
effect(() => {
localStorage.setItem('auto-advance', this.autoAdvance().toString());
});
effect(() => {
const active = this.keepScreenOn();
localStorage.setItem('keep-screen-on', active.toString());
if (active) {
this.requestWakeLock();
} else {
this.releaseWakeLock();
}
});
// Re-request on visibility change
document.addEventListener('visibilitychange', () => {
if (this.keepScreenOn() && document.visibilityState === 'visible') {
this.requestWakeLock();
}
});
}
setShowChordsDefault(val: boolean) {
this.showChordsDefault.set(val);
}
toggleFullscreenMode() {
this.fullscreenMode.update(v => !v);
}
toggleAutoAdvance() {
this.autoAdvance.update(v => !v);
}
toggleEditor() {
const newValue = !this.showEditor();
this.showEditor.set(newValue);
localStorage.setItem('show-editor', newValue.toString());
}
toggleKeepScreenOn() {
this.keepScreenOn.update(v => !v);
}
private async requestWakeLock() {
if ('wakeLock' in navigator) {
try {
this.wakeLock = await (navigator as any).wakeLock.request('screen');
} catch (err: any) {
console.error(`Wake Lock error: ${err.name}, ${err.message}`);
}
}
}
private releaseWakeLock() {
if (this.wakeLock) {
this.wakeLock.release();
this.wakeLock = null;
}
}
toggleBrowserFullscreen() {
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen().catch(err => {
console.error(`Error attempting to enable full-screen mode: ${err.message}`);
});
} else {
if (document.exitFullscreen) {
document.exitFullscreen();
}
}
}
}
+31
View File
@@ -0,0 +1,31 @@
import { Injectable, signal, effect } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class ThemeService {
public highContrast = signal<boolean>(false);
constructor() {
// Load from localStorage
const saved = localStorage.getItem('high-contrast');
if (saved === 'true') {
this.highContrast.set(true);
}
// Effect to apply class to body
effect(() => {
const isHigh = this.highContrast();
if (isHigh) {
document.body.classList.add('high-contrast');
} else {
document.body.classList.remove('high-contrast');
}
localStorage.setItem('high-contrast', isHigh.toString());
});
}
toggleContrast() {
this.highContrast.update(v => !v);
}
}
+247
View File
@@ -0,0 +1,247 @@
import { Injectable, signal, effect, inject } from '@angular/core';
import { CantiService } from './canti.service';
import { SettingsService } from './settings.service';
import { MediaSessionService } from './media-session.service';
import { MyCantiService } from './my-canti.service';
@Injectable({
providedIn: 'root'
})
export class YoutubePlayerService {
private cantiService = inject(CantiService);
private settingsService = inject(SettingsService);
private mediaSessionService = inject(MediaSessionService);
private myCantiService = inject(MyCantiService);
public currentCantoId = signal<string | null>(null);
public isPlaying = signal<boolean>(false);
public videoProgress = signal<number>(0);
public videoDuration = signal<number>(0);
public isPlayerReady = signal<boolean>(false);
private player: any = null;
private progressInterval: any = null;
private onEndedCallback: (() => void) | null = null;
private onErrorCallback: (() => void) | null = null;
private silentAudio: HTMLAudioElement | null = null;
private lastNextCallback: (() => void) | null = null;
private lastPrevCallback: (() => void) | null = null;
constructor() {
this.loadYoutubeAPI();
this.setupMediaSession();
this.initSilentAudio();
this.setupBackgroundPersistence();
}
private initSilentAudio() {
// 1-second silent MP3 base64
const silentSrc = 'data:audio/mpeg;base64,SUQzBAAAAAABAFRYWFhYAAAADAAAY29udGVudAB0eXBlAGF1ZGlvL21wZWdB///+8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
this.silentAudio = new Audio(silentSrc);
this.silentAudio.loop = true;
}
private setupBackgroundPersistence() {
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible' && this.isPlaying() && this.player) {
// Ensure player is actually playing when returning to the app
try {
if (this.player.getPlayerState() !== (window as any).YT.PlayerState.PLAYING) {
this.player.playVideo();
}
} catch (e) {}
}
});
}
public setMediaSessionCallbacks(next?: () => void, prev?: () => void) {
if (next) this.lastNextCallback = next;
if (prev) this.lastPrevCallback = prev;
this.mediaSessionService.initActionHandlers({
play: () => this.resume(),
pause: () => this.pause(),
seekto: (time) => this.seekTo(time),
next: this.lastNextCallback || undefined,
prev: this.lastPrevCallback || undefined
});
}
private setupMediaSession() {
this.setMediaSessionCallbacks();
}
private loadYoutubeAPI() {
if ((window as any).YT) return;
const tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
const firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode?.insertBefore(tag, firstScriptTag);
(window as any).onYouTubeIframeAPIReady = () => {
this.isPlayerReady.set(true);
};
}
public initPlayer(cantoId: string, startTime: number = 0, onEnded?: () => void, onError?: () => void) {
if (this.currentCantoId() === cantoId && this.player) {
this.onEndedCallback = onEnded || null;
this.onErrorCallback = onError || null;
const currentTime = this.player.getCurrentTime();
// Only seek if the difference is significant (more than 2 seconds)
if (startTime > 0 && Math.abs(currentTime - startTime) > 2) {
this.player.seekTo(startTime, true);
}
this.resume();
return;
}
this.onEndedCallback = onEnded || null;
this.onErrorCallback = onError || null;
let canto = this.cantiService.getCantoById(cantoId);
if (!canto) {
canto = this.myCantiService.myCanti().find(c => c.id === cantoId);
}
if (!canto) return;
const videoId = this.cantiService.getYoutubeId(canto.link_youtube);
if (!videoId) {
if (onError) onError();
return;
}
if (!(window as any).YT || !(window as any).YT.Player) {
setTimeout(() => this.initPlayer(cantoId, startTime, onEnded, onError), 200);
return;
}
// Reuse existing player if possible
if (this.player && this.player.loadVideoById) {
this.currentCantoId.set(cantoId);
this.mediaSessionService.updateMetadata(cantoId);
this.player.loadVideoById({
videoId: videoId,
startSeconds: startTime
});
if (this.silentAudio) this.silentAudio.play().catch(() => {});
return;
}
this.destroyPlayer();
this.currentCantoId.set(cantoId);
this.mediaSessionService.updateMetadata(cantoId);
this.player = new (window as any).YT.Player('global-yt-player-container', {
height: '1',
width: '1',
videoId: videoId,
playerVars: {
autoplay: 1,
playsinline: 1,
mute: 0,
modestbranding: 1,
rel: 0,
controls: 0,
disablekb: 1,
start: startTime
},
events: {
onReady: (event: any) => {
event.target.unMute();
event.target.setVolume(100);
this.videoDuration.set(event.target.getDuration());
this.startPolling();
if (startTime > 0) {
event.target.seekTo(startTime, true);
}
event.target.playVideo();
this.isPlaying.set(true);
if (this.silentAudio) this.silentAudio.play().catch(() => {});
},
onStateChange: (event: any) => {
const state = event.data;
if (state === (window as any).YT.PlayerState.PLAYING) {
this.isPlaying.set(true);
this.videoDuration.set(this.player.getDuration());
this.mediaSessionService.setPlaybackState('playing');
// Re-apply handlers to prevent YT from overriding them
this.setMediaSessionCallbacks();
} else if (state === (window as any).YT.PlayerState.PAUSED) {
this.isPlaying.set(false);
this.mediaSessionService.setPlaybackState('paused');
// Re-apply handlers even when paused
this.setMediaSessionCallbacks();
} else if (state === (window as any).YT.PlayerState.ENDED) {
this.isPlaying.set(false);
this.mediaSessionService.setPlaybackState('none');
if (this.onEndedCallback) this.onEndedCallback();
}
},
onError: (event: any) => {
console.error('Global YT Player Error:', event.data);
if (this.onErrorCallback) this.onErrorCallback();
}
}
});
}
public pause() {
if (this.player) {
this.player.pauseVideo();
this.isPlaying.set(false);
if (this.silentAudio) this.silentAudio.pause();
}
}
public resume() {
if (this.player) {
this.player.playVideo();
this.isPlaying.set(true);
if (this.silentAudio) this.silentAudio.play().catch(() => {});
}
}
public togglePlayPause() {
if (this.isPlaying()) {
this.pause();
} else {
this.resume();
}
}
public seekTo(seconds: number) {
if (this.player) {
this.player.seekTo(seconds, true);
}
}
public stop() {
this.destroyPlayer();
this.currentCantoId.set(null);
this.isPlaying.set(false);
}
private startPolling() {
if (this.progressInterval) clearInterval(this.progressInterval);
this.progressInterval = setInterval(() => {
if (this.player && this.player.getCurrentTime) {
this.videoProgress.set(this.player.getCurrentTime());
}
}, 500);
}
private destroyPlayer() {
if (this.progressInterval) {
clearInterval(this.progressInterval);
this.progressInterval = null;
}
if (this.player) {
try {
this.player.destroy();
} catch (e) {}
this.player = null;
}
}
}
+1
View File
@@ -0,0 +1 @@
export const VERSION = '2026.05.16.1715';