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
+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);
}
}