MireaFrontend/src/services/tab-storage.service.ts

87 lines
2.1 KiB
TypeScript
Raw Normal View History

2024-08-23 23:19:25 +03:00
import {MatChipListbox} from "@angular/material/chips";
2024-08-28 02:01:39 +03:00
import {Injectable} from "@angular/core";
2024-08-23 23:19:25 +03:00
export class TabSelect {
public index: number;
public name: string;
constructor(index: number, name: string) {
this.index = index;
this.name = name;
}
}
export enum TabSelectType {
group,
professor,
lecture,
other
}
export interface TabSelectData {
selected: TabSelect[] | null;
type: TabSelectType;
}
2024-08-28 02:01:39 +03:00
@Injectable({
providedIn: 'root'
})
export class TabStorageService {
2024-08-23 23:19:25 +03:00
private static dataName = 'tabSelectedData';
public static trySelectChip(index: number, chip: MatChipListbox, tryCount: number = 0) {
setTimeout(() => {
if (chip?._chips !== undefined && chip._chips.length !== 0) {
let selected = chip._chips.find(x => x.value == index.toString());
if (selected !== undefined) {
selected.select();
return;
}
}
2024-08-28 01:53:55 +03:00
if (tryCount < 10)
this.trySelectChip(index, chip, ++tryCount);
else
2024-08-23 23:19:25 +03:00
return;
}, 100);
}
public static select(selected: TabSelect, type: TabSelectType, index: number) {
let selectedData = this.selected;
if (selectedData === null)
selectedData = {} as TabSelectData;
if (selectedData.type !== type || selectedData.selected === null || selectedData.selected.length === 0) {
if (index !== 0)
return;
else
selectedData.selected = [selected];
} else {
if (selectedData.selected.length < index)
return;
if (selectedData.selected.length - 1 === index)
selectedData.selected[index] = selected;
else if (selectedData.selected.length > index + 1)
selectedData.selected = selectedData.selected.slice(0, index + 1);
else
selectedData.selected.push(selected);
}
selectedData.type = type;
localStorage.setItem(this.dataName, JSON.stringify(selectedData));
}
public static get selected(): TabSelectData | null {
let data = localStorage.getItem(this.dataName);
if (data === null)
return null;
return JSON.parse(data) as TabSelectData;
}
}