All files / frontend/components/ArchSwitcher recentArchitectures.ts

96.38% Statements 80/83
97.05% Branches 66/68
86.66% Functions 13/15
98.41% Lines 62/63

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155                                      5x   5x 5x                         31x 31x 29x             81x 79x 79x 161x 159x 159x 157x 154x 154x 150x         79x 89x         69x 65x 65x 65x 48x   1x 1x                 36x 34x 28x     34x 34x   1x   34x               18x 18x 18x 61x   18x 18x 42x 27x 27x   18x       176x                 32x 32x 32x 19x 60x 60x 60x                       26x 24x 88x 88x 12x   24x 24x 30x 10x 5x 5x 5x    
/*
  Copyright (C) 2026 Sber
 
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
 
          http://www.apache.org/licenses/LICENSE-2.0
 
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
 
import { getLoggerWithTag } from '@global/logger/v2/logger.mjs';
import type { UserRight } from '@front/store/userRight';
 
export const RECENT_ARCHITECTURES_KEY = 'seaf.archSwitcher.recent';
 
const logger = getLoggerWithTag('ArchSwitcher');
const RECENT_LIMIT = 4;
 
export interface RecentEntry {
  alias: string;
  usedAt: number;
}
 
interface RecentStorage {
  getItem(key: string): string | null;
  setItem(key: string, value: string): void;
}
 
function defaultStorage(): RecentStorage | null {
  try {
    if (typeof sessionStorage === 'undefined') return null;
    return sessionStorage;
  } catch {
    return null;
  }
}
 
function normalize(parsed: unknown): RecentEntry[] {
  if (!Array.isArray(parsed)) return [];
  const byAlias = new Map<string, RecentEntry>();
  for (const item of parsed) {
    if (!item || typeof item !== 'object') continue;
    const row = item as { alias?: unknown; usedAt?: unknown };
    if (!row.alias || typeof row.alias !== 'string') continue;
    if (typeof row.usedAt !== 'number' || !Number.isFinite(row.usedAt)) continue;
    const prev = byAlias.get(row.alias);
    if (prev && prev.usedAt > row.usedAt) continue;
    byAlias.set(row.alias, {
      alias: row.alias,
      usedAt: row.usedAt
    });
  }
  return [...byAlias.values()]
    .sort((a, b) => b.usedAt - a.usedAt)
    .slice(0, RECENT_LIMIT);
}
 
export function readRecent(storage: RecentStorage | null = defaultStorage()): RecentEntry[] {
  if (!storage) return [];
  try {
    const raw = storage.getItem(RECENT_ARCHITECTURES_KEY);
    if (!raw) return [];
    return normalize(JSON.parse(raw));
  } catch {
    logger.warn(() => `Failed to get item ${RECENT_ARCHITECTURES_KEY} from storage`);
    return [];
  }
}
 
export function remember(
  alias: string,
  storage: RecentStorage | null = defaultStorage(),
  now: number = Date.now()
): RecentEntry[] {
  if (!alias || !storage) return readRecent(storage);
  const next = normalize([
    ...readRecent(storage).filter((item) => item.alias !== alias),
    {alias, usedAt: now}
  ]);
  try {
    storage.setItem(RECENT_ARCHITECTURES_KEY, JSON.stringify(next));
  } catch {
    logger.warn(() => `Failed to set item ${RECENT_ARCHITECTURES_KEY} in storage`);
  }
  return next;
}
 
export function recentSection<T extends UserRight>(
  rights: readonly T[] | null | undefined,
  currentAlias: string,
  storage: RecentStorage | null = defaultStorage()
): T[] {
  const list = Array.isArray(rights) ? rights : [];
  const byAlias = new Map<string, T>();
  for (const right of list) {
    if (right?.alias) byAlias.set(right.alias, right);
  }
  const matched: T[] = [];
  for (const item of readRecent(storage)) {
    if (item.alias === currentAlias) continue;
    const right = byAlias.get(item.alias);
    if (right) matched.push(right);
  }
  return matched;
}
 
function sortLabel(right: UserRight | null | undefined): string {
  return right?.title || right?.alias || '';
}
 
// Локальный фильтр секции ВСЕ: подстрока без учёта регистра по title ИЛИ alias
// Пустой или пробельный запрос возвращает список как есть.
export function filterByQuery<T extends UserRight>(
  rights: readonly T[] | null | undefined,
  query: string
): T[] {
  const list = Array.isArray(rights) ? [...rights] : [];
  const needle = (query || '').trim().toLowerCase();
  if (!needle) return list;
  return list.filter((right) => {
    const title = (right?.title || '').toLowerCase();
    const alias = (right?.alias || '').toLowerCase();
    return title.includes(needle) || alias.includes(needle);
  });
}
 
export interface AllSortedOptions {
  allFirstAlias?: string;
}
 
export function allSorted<T extends UserRight>(
  rights: readonly T[] | null | undefined,
  options: AllSortedOptions = {}
): T[] {
  if (!Array.isArray(rights)) return [];
  const sorted = [...rights].sort((a, b) => {
    const byLabel = sortLabel(a).localeCompare(sortLabel(b), 'ru');
    if (byLabel !== 0) return byLabel;
    return (a?.alias || '').localeCompare(b?.alias || '', 'ru');
  });
  const allFirstAlias = options.allFirstAlias;
  if (!allFirstAlias) return sorted;
  const index = sorted.findIndex((right) => right?.alias === allFirstAlias);
  if (index <= 0) return sorted;
  const [first] = sorted.splice(index, 1);
  sorted.unshift(first);
  return sorted;
}