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

106 lines
2.7 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";
import {Params, Router} from "@angular/router";
import {Location} from '@angular/common';
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: { [key: string]: TabSelect };
type: TabSelectType | null;
2024-08-23 23:19:25 +03:00
}
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';
private _enclosure: string[] = [];
2024-08-23 23:19:25 +03:00
constructor(private router: Router, private location: Location) {
}
2024-08-23 23:19:25 +03:00
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 set enclosure(data: string[]) {
this._enclosure = data;
}
public select(type: TabSelectType, tabSelected: TabSelect[]) {
let selectedData = {selected: {}} as TabSelectData;
for (let index = 0; index < this._enclosure.length; index++) {
if (tabSelected[index])
selectedData.selected[this._enclosure[index]] = tabSelected[index];
}
2024-08-23 23:19:25 +03:00
selectedData.type = type;
localStorage.setItem(TabStorageService.dataName, JSON.stringify(selectedData));
const currentUrl = this.router.url.split('?')[0];
const queryParam = new URLSearchParams();
for (let select in selectedData.selected)
queryParam.set(select, selectedData.selected[select].name);
this.location.replaceState(currentUrl, queryParam.toString());
}
public static selectDataFromQuery(query: Params) {
if (Object.keys(query).length === 0)
return;
let selectedData = {selected: {}} as TabSelectData;
selectedData.type = null;
for (let select in query) {
selectedData.selected[select] = {} as TabSelect;
selectedData.selected[select].name = query[select];
selectedData.selected[select].index = -1;
}
localStorage.setItem(TabStorageService.dataName, JSON.stringify(selectedData));
2024-08-23 23:19:25 +03:00
}
public static get selected(): TabSelectData | null {
let data = localStorage.getItem(this.dataName);
if (data === null)
return null;
return JSON.parse(data) as TabSelectData;
}
}