53 lines
1.7 KiB
TypeScript
53 lines
1.7 KiB
TypeScript
import { Injectable, inject } from '@angular/core';
|
|
import { CanDeactivate } from '@angular/router';
|
|
import { Observable } from 'rxjs';
|
|
import { EditorStateService } from '../../../services/editor-state.service';
|
|
|
|
/**
|
|
* Interface pour les composants qui peuvent être désactivés
|
|
*/
|
|
export interface CanComponentDeactivate {
|
|
canDeactivate: () => Observable<boolean> | Promise<boolean> | boolean;
|
|
}
|
|
|
|
/**
|
|
* Guard de navigation pour protéger contre la perte de données non sauvegardées
|
|
* Utilisé pour empêcher l'utilisateur de quitter une page avec des modifications en cours
|
|
*/
|
|
@Injectable({
|
|
providedIn: 'root'
|
|
})
|
|
export class EditorCanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
|
|
private editorState = inject(EditorStateService);
|
|
|
|
canDeactivate(
|
|
component: CanComponentDeactivate
|
|
): Observable<boolean> | Promise<boolean> | boolean {
|
|
|
|
// Si pas en mode édition ou pas de modifications, autoriser la navigation
|
|
if (!this.editorState.isEditMode() || this.editorState.canExit()) {
|
|
return true;
|
|
}
|
|
|
|
// Sinon, demander confirmation
|
|
const message = 'You have unsaved changes. Do you really want to leave?';
|
|
return confirm(message);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Hook beforeunload pour protéger contre la fermeture du navigateur
|
|
* À utiliser dans le composant racine (app.component.ts)
|
|
*/
|
|
export function setupBeforeUnloadGuard(editorState: EditorStateService): void {
|
|
if (typeof window === 'undefined') return;
|
|
|
|
window.addEventListener('beforeunload', (event) => {
|
|
if (editorState.isEditMode() && !editorState.canExit()) {
|
|
event.preventDefault();
|
|
event.returnValue = 'You have unsaved changes. Are you sure you want to leave?';
|
|
return event.returnValue;
|
|
}
|
|
});
|
|
}
|