lems-select.service.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { Injectable } from '@angular/core';
  2. import { Subject } from 'rxjs';
  3. import { shareReplay } from 'rxjs/operators';
  4. import { AppConfig } from '../app.config';
  5. import { LemsSelectItem } from '../components/lems-select/lems-select.component';
  6. import { Attributes } from '../models/evt-models';
  7. @Injectable({
  8. providedIn: 'root',
  9. })
  10. export class LemsSelectService {
  11. public updateLemsSelection$ = new Subject<LemsSelectItem[]>();
  12. public selectedLemsItems$ = this.updateLemsSelection$.pipe(
  13. shareReplay(1),
  14. );
  15. public getClassNameFromValue(value) {
  16. return value.toLowerCase().replace(/\s/g, '').replace(/(\[.*?\])/g, '');
  17. }
  18. public getAttributesFromValue(value): Array<{ key: string, value: string }> {
  19. return (value.toLowerCase().replace(/\s/g, '').match(/(\[.*?\])/g) || [])
  20. .map(i => i.replace(/(\[|\]|\')/g, '').split('=')).map(i => ({ key: i[0], value: i[1] }));
  21. }
  22. public matchClassAndAttributes(valueForCheck: string, attributesToCheck: Attributes, classToCheck: string) {
  23. return valueForCheck.split(',')
  24. .some(v => this.matchClass(v, classToCheck) && this.matchAttributes(v, attributesToCheck));
  25. }
  26. public matchClass(classForCheck: string, classToCheck: string) {
  27. return classToCheck === this.getClassNameFromValue(classForCheck);
  28. }
  29. public matchAttributes(attributesForCheck: string, attributesToCheck: Attributes) {
  30. return this.getAttributesFromValue(attributesForCheck).every(a => attributesToCheck[a.key] === a.value);
  31. }
  32. public getHighlightColor(attributesToCheck: Attributes, classNameToCheck: string, selectedLemsItems?: LemsSelectItem[]) {
  33. const lemsSelectItems = AppConfig.evtSettings.edition.lemsSelectItems
  34. .reduce((i: LemsSelectItem[], g) => i.concat(g.items), [])
  35. .reduce((x: LemsSelectItem[], y) => {
  36. const multiValues: LemsSelectItem[] = [];
  37. y.value.split(',').forEach(t => {
  38. multiValues.push({ ...y, value: t });
  39. });
  40. return x.concat(multiValues);
  41. }, []);
  42. let bestMatch: LemsSelectItem & { score: number };
  43. lemsSelectItems.forEach(item => {
  44. let score = 0;
  45. score += this.matchClass(item.value, classNameToCheck) ? 1 : 0;
  46. const attributes = this.getAttributesFromValue(item.value);
  47. score += attributes.length && this.matchAttributes(item.value, attributesToCheck) ? 1 : 0;
  48. if (score > 0 && selectedLemsItems) {
  49. score += selectedLemsItems.find(i => i.value === item.value) ? 1 : 0;
  50. }
  51. if (score > 0 && (!bestMatch || bestMatch.score < score)) {
  52. bestMatch = {
  53. ...item,
  54. score,
  55. };
  56. }
  57. });
  58. return bestMatch ? bestMatch.color : '';
  59. }
  60. }