MireaFrontend/src/services/tab-storage.service.ts
Polianin Nikita 380b2efa0d
All checks were successful
Build and Deploy Angular App / build (push) Successful in 2m3s
fix: delete data if top-level data is selected
2024-09-30 04:55:33 +03:00

106 lines
2.7 KiB
TypeScript

import {MatChipListbox} from "@angular/material/chips";
import {Injectable} from "@angular/core";
import {Params, Router} from "@angular/router";
import {Location} from '@angular/common';
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;
}
@Injectable({
providedIn: 'root'
})
export class TabStorageService {
private static dataName = 'tabSelectedData';
private _enclosure: string[] = [];
constructor(private router: Router, private location: Location) {
}
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;
}
}
if (tryCount < 10)
this.trySelectChip(index, chip, ++tryCount);
else
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];
}
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));
}
public static get selected(): TabSelectData | null {
let data = localStorage.getItem(this.dataName);
if (data === null)
return null;
return JSON.parse(data) as TabSelectData;
}
}