refactor: delete all playlists feature

- Updated confirmation dialog messages to provide detailed consequences of deleting playlists.
- Added backup hints and progress messages for better user experience during playlist deletion.
- Ensured consistency in language across all supported translations (de, el, en, es, fr, it, ja, ko, nl, pl, pt, ru, tr, zh, zhtw).

Entire-Checkpoint: c6e522b4276c
This commit is contained in:
4gray committed 2026-04-21 20:09:05 +02:00
1 parent d7114c1580
commit fc3db71e85
27 files changed
+1140 -233

No files matched your search

@@ -0,0 +1,55 @@
<h2 mat-dialog-title>
{{ 'SETTINGS.REMOVE_DIALOG.TITLE' | translate }}
</h2>
<mat-dialog-content class="mat-typography settings-delete-dialog">
<p class="settings-delete-dialog__lead">
{{
'SETTINGS.REMOVE_DIALOG.MESSAGE'
| translate: { count: dialogData.summary.total }
}}
</p>
<section class="settings-delete-dialog__section">
<h3 class="settings-delete-dialog__section-title">
{{ 'SETTINGS.REMOVE_DIALOG.SUMMARY_TITLE' | translate }}
</h3>
<div class="settings-delete-dialog__summary">
@for (item of summaryItems(); track item.id) {
<div class="settings-delete-dialog__summary-item">
<div class="settings-delete-dialog__summary-label">
<mat-icon aria-hidden="true">{{ item.icon }}</mat-icon>
<span>{{ item.labelKey | translate }}</span>
</div>
<strong>{{ item.count }}</strong>
</div>
}
</div>
</section>
<section class="settings-delete-dialog__section">
<h3 class="settings-delete-dialog__section-title">
{{ 'SETTINGS.REMOVE_DIALOG.CONSEQUENCES_TITLE' | translate }}
</h3>
<ul class="settings-delete-dialog__list">
@for (key of consequenceKeys; track key) {
<li>{{ key | translate }}</li>
}
</ul>
</section>
<p class="settings-delete-dialog__hint">
{{ 'SETTINGS.REMOVE_DIALOG.BACKUP_HINT' | translate }}
</p>
</mat-dialog-content>
<mat-dialog-actions align="end" class="settings-delete-dialog__actions">
<button mat-button mat-dialog-close cdkFocusInitial>
{{ 'CANCEL' | translate }}
</button>
<button mat-flat-button [mat-dialog-close]="true" color="warn">
{{ 'SETTINGS.REMOVE_DIALOG.CONFIRM' | translate }}
</button>
</mat-dialog-actions>
@@ -0,0 +1,94 @@
:host {
display: block;
}
.settings-delete-dialog {
display: flex;
flex-direction: column;
gap: 18px;
min-width: min(100%, 360px);
}
.settings-delete-dialog__lead,
.settings-delete-dialog__hint {
margin: 0;
line-height: 1.55;
text-wrap: pretty;
}
.settings-delete-dialog__section {
display: flex;
flex-direction: column;
gap: 10px;
}
.settings-delete-dialog__section-title {
margin: 0;
font-size: 0.8rem;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
color: var(--mat-sys-on-surface-variant);
}
.settings-delete-dialog__summary {
display: grid;
gap: 8px;
}
.settings-delete-dialog__summary-item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 10px 12px;
border: 1px solid
color-mix(in srgb, var(--mat-sys-outline) 46%, transparent);
border-radius: 14px;
background: color-mix(
in srgb,
var(--mat-sys-surface-container) 84%,
transparent
);
strong {
font-size: 1rem;
font-variant-numeric: tabular-nums;
}
}
.settings-delete-dialog__summary-label {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
}
.settings-delete-dialog__summary-label mat-icon {
width: 18px;
height: 18px;
font-size: 18px;
color: var(--mat-sys-primary);
}
.settings-delete-dialog__list {
margin: 0;
padding-left: 20px;
display: grid;
gap: 8px;
}
.settings-delete-dialog__hint {
padding: 12px 14px;
border-radius: 14px;
background: color-mix(
in srgb,
var(--app-selection-surface) 32%,
transparent
);
color: var(--mat-sys-on-surface-variant);
}
.settings-delete-dialog__actions {
padding-top: 2px;
}
@@ -0,0 +1,96 @@
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { SettingsDeleteAllPlaylistsDialogComponent } from './settings-delete-all-playlists-dialog.component';
describe('SettingsDeleteAllPlaylistsDialogComponent', () => {
let component: SettingsDeleteAllPlaylistsDialogComponent;
let fixture: ComponentFixture<SettingsDeleteAllPlaylistsDialogComponent>;
let translate: TranslateService;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
SettingsDeleteAllPlaylistsDialogComponent,
NoopAnimationsModule,
TranslateModule.forRoot(),
],
providers: [
{
provide: MAT_DIALOG_DATA,
useValue: {
summary: {
total: 6,
m3u: 3,
xtream: 2,
stalker: 1,
},
},
},
],
}).compileComponents();
translate = TestBed.inject(TranslateService);
translate.setTranslation(
'en',
{
CANCEL: 'Cancel',
HOME: {
PLAYLIST_TYPES: {
M3U: 'M3U',
XTREAM: 'Xtream',
STALKER: 'Stalker',
},
},
SETTINGS: {
REMOVE_DIALOG: {
TITLE: 'Delete all playlists?',
MESSAGE: 'Delete all {{count}} playlists from the app.',
SUMMARY_TITLE: 'Playlist sources',
CONSEQUENCES_TITLE: 'This also removes',
CONSEQUENCE_FAVORITES: 'Favorites',
CONSEQUENCE_RECENTLY_VIEWED: 'Recently viewed history',
CONSEQUENCE_PLAYBACK: 'Playback positions',
CONSEQUENCE_DOWNLOADS: 'Download history',
CONSEQUENCE_XTREAM_CACHE: 'Xtream cache',
BACKUP_HINT: 'Use Export first if you need a backup.',
CONFIRM: 'Delete everything',
},
},
},
true
);
translate.use('en');
fixture = TestBed.createComponent(
SettingsDeleteAllPlaylistsDialogComponent
);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('renders the playlist type summary and destructive guidance', () => {
const text = (fixture.nativeElement as HTMLElement).textContent ?? '';
expect(component.summaryItems().map((item) => item.count)).toEqual([
3, 2, 1,
]);
expect(text).toContain('Delete all playlists?');
expect(text).toContain('Delete all 6 playlists from the app.');
expect(text).toContain('Playlist sources');
expect(text).toContain('M3U');
expect(text).toContain('Xtream');
expect(text).toContain('Stalker');
expect(text).toContain('Favorites');
expect(text).toContain('Use Export first if you need a backup.');
});
it('renders cancel and confirm actions', () => {
const buttons = Array.from(
(fixture.nativeElement as HTMLElement).querySelectorAll('button')
).map((button) => button.textContent?.trim());
expect(buttons).toEqual(['Cancel', 'Delete everything']);
});
});
@@ -0,0 +1,68 @@
import { CommonModule } from '@angular/common';
import { Component, computed, inject } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatDialogModule, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
import { TranslateModule } from '@ngx-translate/core';
export interface SettingsDeleteAllPlaylistsDialogData {
summary: {
total: number;
m3u: number;
xtream: number;
stalker: number;
};
}
type SettingsDeleteSummaryItem = {
count: number;
icon: string;
id: 'm3u' | 'xtream' | 'stalker';
labelKey: string;
};
@Component({
selector: 'app-settings-delete-all-playlists-dialog',
templateUrl: './settings-delete-all-playlists-dialog.component.html',
styleUrls: ['./settings-delete-all-playlists-dialog.component.scss'],
imports: [
CommonModule,
MatButtonModule,
MatDialogModule,
MatIconModule,
TranslateModule,
],
})
export class SettingsDeleteAllPlaylistsDialogComponent {
readonly dialogData =
inject<SettingsDeleteAllPlaylistsDialogData>(MAT_DIALOG_DATA);
readonly summaryItems = computed<SettingsDeleteSummaryItem[]>(() => [
{
id: 'm3u',
count: this.dialogData.summary.m3u,
icon: 'playlist_play',
labelKey: 'HOME.PLAYLIST_TYPES.M3U',
},
{
id: 'xtream',
count: this.dialogData.summary.xtream,
icon: 'cloud',
labelKey: 'HOME.PLAYLIST_TYPES.XTREAM',
},
{
id: 'stalker',
count: this.dialogData.summary.stalker,
icon: 'router',
labelKey: 'HOME.PLAYLIST_TYPES.STALKER',
},
]);
readonly consequenceKeys = [
'SETTINGS.REMOVE_DIALOG.CONSEQUENCE_FAVORITES',
'SETTINGS.REMOVE_DIALOG.CONSEQUENCE_RECENTLY_VIEWED',
'SETTINGS.REMOVE_DIALOG.CONSEQUENCE_PLAYBACK',
'SETTINGS.REMOVE_DIALOG.CONSEQUENCE_DOWNLOADS',
'SETTINGS.REMOVE_DIALOG.CONSEQUENCE_XTREAM_CACHE',
] as const;
}
@@ -501,8 +501,7 @@
mat-button
type="button"
[disabled]="
epgUrl.length === 0 ||
isClearingEpgData()
epgUrl.length === 0 || isClearingEpgData()
"
(click)="refreshAllEpg()"
>
@@ -522,7 +521,9 @@
diameter="16"
mode="indeterminate"
/>
{{ 'SETTINGS.CLEARING_EPG_DATA' | translate }}
{{
'SETTINGS.CLEARING_EPG_DATA' | translate
}}
} @else {
{{ 'SETTINGS.CLEAR_EPG_DATA' | translate }}
}
@@ -808,10 +809,41 @@
<p>
{{ 'SETTINGS.REMOVE_ALL_DESCRIPTION' | translate }}
</p>
<div class="danger-zone__summary" aria-live="polite">
<span class="danger-zone__summary-pill">
{{ 'HOME.PLAYLIST_TYPES.M3U' | translate }}
<strong>{{
playlistDeleteSummary().m3u
}}</strong>
</span>
<span class="danger-zone__summary-pill">
{{ 'HOME.PLAYLIST_TYPES.XTREAM' | translate }}
<strong>{{
playlistDeleteSummary().xtream
}}</strong>
</span>
<span class="danger-zone__summary-pill">
{{ 'HOME.PLAYLIST_TYPES.STALKER' | translate }}
<strong>{{
playlistDeleteSummary().stalker
}}</strong>
</span>
</div>
@if (removeAllProgressLabel(); as progressLabel) {
<p class="danger-zone__progress">
{{ progressLabel }}
</p>
}
</div>
<div class="setting-item__control">
<button
mat-button
class="danger-zone__button"
[class.danger-zone__button--busy]="
isRemovingAllPlaylists()
"
[disabled]="!canRemoveAllPlaylists()"
[attr.aria-busy]="isRemovingAllPlaylists()"
(click)="
$event.preventDefault();
$event.stopPropagation();
@@ -820,9 +852,19 @@
color="warn"
>
@if (isRemovingAllPlaylists()) {
<mat-spinner diameter="18" strokeWidth="3" />
<mat-progress-spinner
class="button-spinner"
diameter="16"
mode="indeterminate"
/>
<span class="inline-actions__label">{{
'SETTINGS.REMOVE_ALL_IN_PROGRESS'
| translate
}}</span>
} @else {
{{ 'SETTINGS.REMOVE_ALL_BUTTON' | translate }}
<span class="inline-actions__label">{{
'SETTINGS.REMOVE_ALL_BUTTON' | translate
}}</span>
}
</button>
</div>
@@ -1022,8 +1064,7 @@
<span class="support-btn__text">
<strong>Ko-fi</strong>
<small>{{
'SETTINGS.SUPPORT_KOFI_HINT'
| translate
'SETTINGS.SUPPORT_KOFI_HINT' | translate
}}</small>
</span>
</a>
@@ -113,11 +113,8 @@
width: 40px;
height: 40px;
flex-shrink: 0;
border: 1px solid color-mix(
in srgb,
var(--mat-sys-outline-variant) 74%,
transparent
);
border: 1px solid
color-mix(in srgb, var(--mat-sys-outline-variant) 74%, transparent);
border-radius: 12px;
background: color-mix(
in srgb,
@@ -229,11 +226,8 @@
gap: 8px;
min-height: 54px;
padding: 12px 14px;
border: 1px solid color-mix(
in srgb,
var(--mat-sys-outline-variant) 70%,
transparent
);
border: 1px solid
color-mix(in srgb, var(--mat-sys-outline-variant) 70%, transparent);
border-radius: 16px;
background: color-mix(
in srgb,
@@ -291,11 +285,8 @@
);
color: var(--app-selection-color);
box-shadow:
inset 0 0 0 1px color-mix(
in srgb,
var(--app-selection-border) 54%,
transparent
),
inset 0 0 0 1px
color-mix(in srgb, var(--app-selection-border) 54%, transparent),
0 10px 18px -22px var(--settings-group-active-glow);
}
@@ -325,12 +316,12 @@
justify-content: flex-end;
flex-wrap: wrap;
gap: 6px;
}
.button-spinner {
display: inline-block;
margin-right: 6px;
vertical-align: middle;
}
.button-spinner {
display: inline-block;
margin-right: 6px;
vertical-align: middle;
}
.inline-actions__button {
@@ -345,11 +336,8 @@
);
color: var(--app-selection-color);
box-shadow:
inset 0 0 0 1px color-mix(
in srgb,
var(--app-selection-border) 48%,
transparent
),
inset 0 0 0 1px
color-mix(in srgb, var(--app-selection-border) 48%, transparent),
0 8px 18px -18px var(--settings-group-active-glow);
}
@@ -377,7 +365,8 @@
}
.remote-control-url {
font-family: 'JetBrains Mono', 'SFMono-Regular', Menlo, Monaco, Consolas, monospace;
font-family:
'JetBrains Mono', 'SFMono-Regular', Menlo, Monaco, Consolas, monospace;
color: inherit;
text-decoration: none;
font-size: 0.84rem;
@@ -423,11 +412,8 @@
align-items: center;
gap: 12px;
padding: 12px 14px;
border: 1px solid color-mix(
in srgb,
var(--mat-sys-outline-variant) 70%,
transparent
);
border: 1px solid
color-mix(in srgb, var(--mat-sys-outline-variant) 70%, transparent);
border-radius: 16px;
background: color-mix(
in srgb,
@@ -498,11 +484,7 @@
}
.link-card--github .link-card__glyph {
background: color-mix(
in srgb,
var(--mat-sys-on-surface) 10%,
transparent
);
background: color-mix(in srgb, var(--mat-sys-on-surface) 10%, transparent);
color: var(--mat-sys-on-surface);
}
@@ -557,7 +539,8 @@
border-radius: 14px;
font-size: 0.84rem;
background: color-mix(in srgb, var(--mat-sys-primary) 8%, transparent);
border: 1px solid color-mix(in srgb, var(--mat-sys-primary) 30%, transparent);
border: 1px solid
color-mix(in srgb, var(--mat-sys-primary) 30%, transparent);
line-height: 1.45;
a {
@@ -575,6 +558,54 @@
border-radius: 16px;
}
.danger-zone__summary {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 10px;
}
.danger-zone__summary-pill {
display: inline-flex;
align-items: center;
gap: 8px;
min-height: 32px;
padding: 6px 10px;
border-radius: 999px;
background: color-mix(
in srgb,
var(--mat-sys-surface-container-high) 78%,
transparent
);
border: 1px solid
color-mix(in srgb, var(--settings-item-danger-border) 72%, transparent);
font-size: 0.82rem;
line-height: 1.2;
strong {
font-variant-numeric: tabular-nums;
}
}
.danger-zone__progress {
margin-top: 12px;
margin-bottom: 0;
color: var(--mat-sys-on-surface-variant);
font-size: 0.84rem;
}
.danger-zone__button {
min-width: 138px;
}
.danger-zone__button--busy {
background: color-mix(
in srgb,
var(--settings-item-danger-border) 28%,
transparent
);
}
.action-bar {
position: sticky;
bottom: calc(
@@ -8,6 +8,7 @@ import {
import { MatCardModule } from '@angular/material/card';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatDividerModule } from '@angular/material/divider';
import { MatDialog } from '@angular/material/dialog';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatListModule } from '@angular/material/list';
@@ -17,14 +18,20 @@ import { MatTooltipModule } from '@angular/material/tooltip';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { Store } from '@ngrx/store';
import { provideMockStore } from '@ngrx/store/testing';
import { MockStore, provideMockStore } from '@ngrx/store/testing';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { EpgService } from '@iptvnator/epg/data-access';
import { MockModule, MockProvider } from 'ng-mocks';
import { DialogService } from 'components';
import { DataService, PlaylistBackupService, PlaylistsService } from 'services';
import {
DatabaseService,
DataService,
PlaylistBackupService,
PlaylistsService,
} from 'services';
import {
Language,
PlaylistMeta,
StartupBehavior,
StreamFormat,
Theme,
@@ -34,12 +41,16 @@ import { SettingsComponent } from './settings.component';
import { signal } from '@angular/core';
import { NgxIndexedDBService } from 'ngx-indexed-db';
import { from, of, Subject } from 'rxjs';
import { from, of } from 'rxjs';
import { ElectronServiceStub } from '../services/electron.service.stub';
import { SettingsStore } from '../services/settings-store.service';
import { SettingsService } from '../services/settings.service';
import { SettingsContextService } from '@iptvnator/workspace/shell/util';
import { PlaylistActions } from 'm3u-state';
import {
PlaylistActions,
selectAllPlaylistsMeta,
selectIsEpgAvailable,
} from 'm3u-state';
class MatSnackBarStub {
open = jest.fn();
@@ -110,8 +121,22 @@ describe('SettingsComponent', () => {
let playlistsService: PlaylistsService;
let playlistBackupService: PlaylistBackupService;
let store: Store;
let mockStore: MockStore;
let databaseService: DatabaseService;
let snackBar: MatSnackBarStub;
const originalElectron = window.electron;
const importDate = '2026-04-21T00:00:00.000Z';
const createPlaylistMeta = (
overrides: Partial<PlaylistMeta> = {}
): PlaylistMeta => ({
_id: overrides._id ?? 'playlist-id',
title: overrides.title ?? 'Playlist',
count: overrides.count ?? 10,
importDate: overrides.importDate ?? importDate,
autoRefresh: overrides.autoRefresh ?? false,
...overrides,
});
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
@@ -124,6 +149,9 @@ describe('SettingsComponent', () => {
MockProvider(DialogService, {
openConfirmDialog: jest.fn(),
}),
MockProvider(MatDialog, {
open: jest.fn(),
}),
{ provide: SettingsService, useClass: MockSettingsService },
{ provide: MatSnackBar, useClass: MatSnackBarStub },
{ provide: DataService, useClass: ElectronServiceStub },
@@ -131,7 +159,12 @@ describe('SettingsComponent', () => {
provide: Router,
useClass: MockRouter,
},
provideMockStore(),
provideMockStore({
selectors: [
{ selector: selectAllPlaylistsMeta, value: [] },
{ selector: selectIsEpgAvailable, value: false },
],
}),
{
provide: NgxIndexedDBService,
useValue: {},
@@ -140,6 +173,12 @@ describe('SettingsComponent', () => {
getAllData: jest.fn().mockReturnValue(of([])),
removeAll: jest.fn(),
}),
MockProvider(DatabaseService, {
createOperationId: jest
.fn()
.mockReturnValue('delete-all-op'),
deleteAllPlaylists: jest.fn().mockResolvedValue(true),
}),
MockProvider(PlaylistBackupService, {
exportBackup: jest.fn().mockResolvedValue({
defaultFileName:
@@ -209,9 +248,15 @@ describe('SettingsComponent', () => {
playlistsService = TestBed.inject(PlaylistsService);
playlistBackupService = TestBed.inject(PlaylistBackupService);
store = TestBed.inject(Store);
mockStore = TestBed.inject(MockStore);
databaseService = TestBed.inject(DatabaseService);
snackBar = TestBed.inject(MatSnackBar) as unknown as MatSnackBarStub;
component = fixture.componentInstance;
component.checkAppVersion = jest.fn();
component.fetchLocalIpAddresses = jest
.fn()
.mockResolvedValue(undefined);
fixture.detectChanges();
});
@@ -219,6 +264,12 @@ describe('SettingsComponent', () => {
window.electron = originalElectron;
});
function setPlaylists(playlists: PlaylistMeta[]): void {
mockStore.overrideSelector(selectAllPlaylistsMeta, playlists);
mockStore.refreshState();
fixture.detectChanges();
}
it('should create and init component', () => {
expect(component).toBeTruthy();
});
@@ -397,30 +448,129 @@ describe('SettingsComponent', () => {
});
});
it('removes all playlists with a busy state and dispatches store cleanup after success', async () => {
const removal$ = new Subject<void>();
const dispatchSpy = jest.spyOn(store, 'dispatch');
it('disables the global wipe action when there are no playlists', () => {
setPlaylists([]);
(dialogService.openConfirmDialog as jest.Mock).mockImplementation(
({ onConfirm }: { onConfirm: () => Promise<void> }) => {
void onConfirm();
}
);
(playlistsService.removeAll as jest.Mock).mockReturnValue(
removal$.asObservable()
);
jest.spyOn(translate, 'instant').mockImplementation((key) => key);
const deleteButton = (
fixture.nativeElement as HTMLElement
).querySelector('.danger-zone__button') as HTMLButtonElement | null;
expect(component.canRemoveAllPlaylists()).toBe(false);
expect(deleteButton?.disabled).toBe(true);
});
it('opens the dedicated delete-all dialog with the current playlist type summary', () => {
setPlaylists([
createPlaylistMeta({ _id: 'm3u-1' }),
createPlaylistMeta({
_id: 'xtream-1',
serverUrl: 'http://xtream.example',
}),
createPlaylistMeta({
_id: 'stalker-1',
macAddress: '00:11:22:33:44:55',
}),
]);
const openSpy = jest
.spyOn((component as any).matDialog, 'open')
.mockReturnValue({
afterClosed: () => of(false),
} as any);
component.removeAll();
expect(component.isRemovingAllPlaylists()).toBe(true);
expect(playlistsService.removeAll).toHaveBeenCalled();
expect(component.playlistDeleteSummary()).toEqual({
total: 3,
m3u: 1,
xtream: 1,
stalker: 1,
});
expect(openSpy).toHaveBeenCalledWith(
expect.any(Function),
expect.objectContaining({
data: {
summary: {
total: 3,
m3u: 1,
xtream: 1,
stalker: 1,
},
},
})
);
});
removal$.next();
removal$.complete();
it('tracks Electron delete-all progress and dispatches store cleanup after success', async () => {
setPlaylists([
createPlaylistMeta({ _id: 'm3u-1' }),
createPlaylistMeta({
_id: 'xtream-1',
serverUrl: 'http://xtream.example',
}),
]);
const dispatchSpy = jest.spyOn(store, 'dispatch');
(databaseService.deleteAllPlaylists as jest.Mock).mockClear();
jest.spyOn((component as any).matDialog, 'open').mockReturnValue({
afterClosed: () => of(true),
} as any);
jest.spyOn(translate, 'instant').mockImplementation(
(key: string, params?: Record<string, number>) => {
if (key === 'SETTINGS.REMOVE_ALL_PROGRESS') {
return `${params?.current}/${params?.total}`;
}
return key;
}
);
jest.spyOn(
component as any,
'waitForUiFeedbackFrame'
).mockResolvedValue(undefined);
let resolveDelete: (value: boolean) => void = () => undefined;
(databaseService.deleteAllPlaylists as jest.Mock).mockImplementation(
({
onEvent,
}: {
onEvent?: (event: {
operation: string;
status: string;
current?: number;
total?: number;
}) => void;
}) => {
onEvent?.({
operation: 'delete-all-playlists',
status: 'progress',
current: 3,
total: 7,
});
return new Promise<boolean>((resolve) => {
resolveDelete = resolve;
});
}
);
component.removeAll();
await Promise.resolve();
fixture.detectChanges();
expect(component.isRemovingAllPlaylists()).toBe(true);
expect(component.removeAllProgressLabel()).toBe('3/7');
expect(databaseService.deleteAllPlaylists).toHaveBeenCalledWith(
expect.objectContaining({
operationId: 'delete-all-op',
onEvent: expect.any(Function),
})
);
resolveDelete(true);
await fixture.whenStable();
expect(component.isRemovingAllPlaylists()).toBe(false);
expect(component.removeAllProgress()).toBeNull();
expect(dispatchSpy).toHaveBeenCalledWith(
PlaylistActions.removeAllPlaylists()
);
@@ -436,6 +586,50 @@ describe('SettingsComponent', () => {
);
});
it('falls back to PlaylistsService.removeAll outside Electron', async () => {
fixture.destroy();
window.electron = undefined as unknown as typeof window.electron;
const browserFixture = TestBed.createComponent(SettingsComponent);
const browserComponent = browserFixture.componentInstance;
browserComponent.checkAppVersion = jest.fn();
browserComponent.fetchLocalIpAddresses = jest
.fn()
.mockResolvedValue(undefined);
browserFixture.detectChanges();
mockStore.overrideSelector(selectAllPlaylistsMeta, [
createPlaylistMeta({ _id: 'browser-m3u' }),
]);
mockStore.refreshState();
browserFixture.detectChanges();
jest.spyOn((browserComponent as any).matDialog, 'open').mockReturnValue(
{
afterClosed: () => of(true),
} as any
);
jest.spyOn(
browserComponent as any,
'waitForUiFeedbackFrame'
).mockResolvedValue(undefined);
(databaseService.deleteAllPlaylists as jest.Mock).mockClear();
(playlistsService.removeAll as jest.Mock).mockClear();
(playlistsService.removeAll as jest.Mock).mockReturnValue(
of(undefined)
);
const dispatchSpy = jest.spyOn(store, 'dispatch');
browserComponent.removeAll();
await browserFixture.whenStable();
expect(playlistsService.removeAll).toHaveBeenCalled();
expect(databaseService.deleteAllPlaylists).not.toHaveBeenCalled();
expect(dispatchSpy).toHaveBeenCalledWith(
PlaylistActions.removeAllPlaylists()
);
});
it('shows the save confirmation snackbar at the bottom center with the settings offset class', () => {
jest.spyOn(translate, 'instant').mockReturnValue('Settings saved');
@@ -493,23 +687,19 @@ describe('SettingsComponent', () => {
});
it('shows an export busy state until the backup file has been written', async () => {
let resolveExport: (
value: {
defaultFileName: string;
json: string;
manifest: {
kind: string;
version: number;
exportedAt: string;
includeSecrets: boolean;
playlists: never[];
};
}
) => void = () => undefined;
let resolveExport: (value: {
defaultFileName: string;
json: string;
manifest: {
kind: string;
version: number;
exportedAt: string;
includeSecrets: boolean;
playlists: never[];
};
}) => void = () => undefined;
(
playlistBackupService.exportBackup as jest.Mock
).mockReturnValueOnce(
(playlistBackupService.exportBackup as jest.Mock).mockReturnValueOnce(
new Promise((resolve) => {
resolveExport = resolve;
})
+138 -25
View File
@@ -1,6 +1,7 @@
import { CommonModule } from '@angular/common';
import {
Component,
computed,
ElementRef,
effect,
inject,
@@ -39,9 +40,15 @@ import { EpgService } from '@iptvnator/epg/data-access';
import { EpgSourceStatusComponent } from '@iptvnator/ui/epg';
import { QRCodeComponent } from 'angularx-qrcode';
import { DialogService } from 'components';
import { PlaylistActions, selectIsEpgAvailable } from 'm3u-state';
import {
PlaylistActions,
selectAllPlaylistsMeta,
selectIsEpgAvailable,
} from 'm3u-state';
import { firstValueFrom, take } from 'rxjs';
import {
DatabaseService,
DbOperationEvent,
DataService,
PlaylistBackupImportSummary,
PlaylistBackupService,
@@ -56,6 +63,10 @@ import {
} from 'shared-interfaces';
import { SettingsContextService } from '@iptvnator/workspace/shell/util';
import { SettingsStore } from '../services/settings-store.service';
import {
SettingsDeleteAllPlaylistsDialogComponent,
SettingsDeleteAllPlaylistsDialogData,
} from './settings-delete-all-playlists-dialog.component';
import { SettingsService } from './../services/settings.service';
interface SettingsSection {
@@ -81,6 +92,9 @@ interface StartupBehaviorOption {
labelKey: string;
}
type SettingsPlaylistDeleteSummary =
SettingsDeleteAllPlaylistsDialogData['summary'];
@Component({
templateUrl: './settings.component.html',
styleUrls: ['./settings.component.scss'],
@@ -121,6 +135,7 @@ export class SettingsComponent implements OnInit, OnDestroy {
private playlistBackupService = inject(PlaylistBackupService);
private readonly elementRef = inject(ElementRef<HTMLElement>);
private readonly injector = inject(Injector);
private readonly databaseService = inject(DatabaseService);
private readonly dialogData = inject<{ isDialog: boolean } | null>(
MAT_DIALOG_DATA,
{ optional: true }
@@ -177,6 +192,7 @@ export class SettingsComponent implements OnInit, OnDestroy {
/** EPG availability flag */
epgAvailable$ = this.store.select(selectIsEpgAvailable);
readonly playlists = this.store.selectSignal(selectAllPlaylistsMeta);
readonly themeOptions: ThemeOption[] = [
{
@@ -244,6 +260,7 @@ export class SettingsComponent implements OnInit, OnDestroy {
readonly isRemovingAllPlaylists = signal(false);
readonly isClearingEpgData = signal(false);
readonly isExportingData = signal(false);
readonly removeAllProgress = signal<DbOperationEvent | null>(null);
private settingsStore = inject(SettingsStore);
private sectionObserver?: IntersectionObserver;
@@ -292,6 +309,50 @@ export class SettingsComponent implements OnInit, OnDestroy {
},
];
readonly playlistDeleteSummary = computed<SettingsPlaylistDeleteSummary>(
() => {
const items = this.playlists();
return {
total: items.length,
m3u: items.filter((item) => !item.serverUrl && !item.macAddress)
.length,
xtream: items.filter((item) => Boolean(item.serverUrl)).length,
stalker: items.filter((item) => Boolean(item.macAddress))
.length,
};
}
);
readonly canRemoveAllPlaylists = computed(
() =>
!this.isRemovingAllPlaylists() &&
this.playlistDeleteSummary().total > 0
);
readonly removeAllProgressLabel = computed(() => {
if (!this.isRemovingAllPlaylists()) {
return null;
}
const progress = this.removeAllProgress();
const current = progress?.current;
const total = progress?.total;
if (
typeof current === 'number' &&
typeof total === 'number' &&
total > 0
) {
return this.translate.instant('SETTINGS.REMOVE_ALL_PROGRESS', {
current,
total,
});
}
return this.translate.instant('SETTINGS.REMOVE_ALL_IN_PROGRESS');
});
constructor() {
effect(
() => {
@@ -756,35 +817,87 @@ export class SettingsComponent implements OnInit, OnDestroy {
});
}
removeAll() {
this.dialogService.openConfirmDialog({
title: this.translate.instant('SETTINGS.REMOVE_DIALOG.TITLE'),
message: this.translate.instant('SETTINGS.REMOVE_DIALOG.MESSAGE'),
onConfirm: async (): Promise<void> => {
if (this.isRemovingAllPlaylists()) {
return;
}
removeAll(): void {
if (!this.canRemoveAllPlaylists()) {
return;
}
this.isRemovingAllPlaylists.set(true);
try {
await firstValueFrom(this.playlistsService.removeAll());
this.store.dispatch(PlaylistActions.removeAllPlaylists());
this.openSettingsSnackbar(
this.translate.instant('SETTINGS.PLAYLISTS_REMOVED')
);
} catch (error) {
console.error('Error removing playlists:', error);
this.openSettingsSnackbar(
this.translate.instant('SETTINGS.IMPORT_ERROR')
);
} finally {
this.isRemovingAllPlaylists.set(false);
this.matDialog
.open<
SettingsDeleteAllPlaylistsDialogComponent,
SettingsDeleteAllPlaylistsDialogData,
boolean
>(SettingsDeleteAllPlaylistsDialogComponent, {
autoFocus: false,
data: {
summary: this.playlistDeleteSummary(),
},
maxWidth: 'calc(100vw - 32px)',
restoreFocus: true,
width: '460px',
})
.afterClosed()
.pipe(take(1))
.subscribe((confirmed) => {
if (confirmed) {
void this.removeAllConfirmed();
}
},
});
}
private async removeAllConfirmed(): Promise<void> {
if (this.isRemovingAllPlaylists()) {
return;
}
this.isRemovingAllPlaylists.set(true);
this.removeAllProgress.set(null);
await this.waitForUiFeedbackFrame();
try {
const deleted =
this.isDesktop && window.electron
? await this.deleteAllPlaylistsInElectron()
: await this.deleteAllPlaylistsInBrowser();
if (!deleted) {
throw new Error('Delete all playlists returned success=false');
}
this.store.dispatch(PlaylistActions.removeAllPlaylists());
this.openSettingsSnackbar(
this.translate.instant('SETTINGS.PLAYLISTS_REMOVED')
);
} catch (error) {
console.error('Error removing playlists:', error);
this.openSettingsSnackbar(
this.translate.instant('SETTINGS.PLAYLISTS_REMOVE_FAILED')
);
} finally {
this.removeAllProgress.set(null);
this.isRemovingAllPlaylists.set(false);
}
}
private async deleteAllPlaylistsInElectron(): Promise<boolean> {
return this.databaseService.deleteAllPlaylists({
operationId: this.databaseService.createOperationId(
'settings-delete-all-playlists'
),
onEvent: (event) => this.handleDeleteAllPlaylistsEvent(event),
});
}
private async deleteAllPlaylistsInBrowser(): Promise<boolean> {
await firstValueFrom(this.playlistsService.removeAll());
return true;
}
private handleDeleteAllPlaylistsEvent(event: DbOperationEvent): void {
this.removeAllProgress.set(event);
}
private setupSectionObserver(): void {
if (typeof IntersectionObserver === 'undefined') {
return;