All files / frontend/components/ArchSwitcher breadcrumbs.ts

96.42% Statements 135/140
92.14% Branches 129/140
100% Functions 19/19
97.22% Lines 105/108

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 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235                                    7x 7x 7x                                             2264x 2264x   2x         460x 460x 460x 175x 164x 164x   460x       158x 5x 5x             98x 98x       2283x 2280x   2275x 2275x 2268x       2268x 2268x 2268x           2268x 2264x     525x 525x 525x 257x 257x   525x 525x 525x 525x 505x 505x 505x   460x 460x 164x 164x   164x 164x 164x 128x 132x     394x       235x           526x 516x 516x 516x 2050x 2050x 2048x 2048x 291x 291x   516x       20x 18x 18x   15x 15x 14x 14x 14x                       486x 486x 486x 1997x 1997x 1997x 3x   1994x 1994x     486x 486x   261x 1131x 1131x 261x 261x 521x 519x 519x 519x 519x 519x                     134x 134x 219x               218x 468x 215x   10x 10x 26x   10x               12x 15x 8x    
/*
  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 {SEARCH_RECORD_LINK_HASH} from '@global/search/constants.mjs';
 
const IGNORED_QUERY = new Set(['_sfa-orgctx', '_sfa-origin-orgctx']);
const HAS_SCHEME = /^[a-zA-Z][a-zA-Z0-9+.-]*:/;
const BASE = 'http://local';
 
export interface CrumbRoute {
  fullPath?: string;
  recordKey?: string;
  marked?: boolean;
  distinguishEntityRecords?: boolean;
}
 
export interface MenuCrumb {
  location?: string;
  route?: string;
  title?: string;
  service?: boolean;
}
 
export interface BuildBreadcrumbsArgs {
  menu?: readonly MenuCrumb[] | null;
  route?: CrumbRoute | null;
  origin?: string;
}
 
function samePath(left: string, right: string): boolean {
  try {
    return decodeURI(left) === decodeURI(right);
  } catch {
    return left === right;
  }
}
 
function relevantKeys(params: URLSearchParams): string[] {
  const keys: string[] = [];
  const seen = new Set<string>();
  for (const key of params.keys()) {
    if (IGNORED_QUERY.has(key) || seen.has(key)) continue;
    seen.add(key);
    keys.push(key);
  }
  return keys;
}
 
export function absoluteMenuUrl(route: string, origin: string): URL | null {
  if (!/^(?:https?:)?\/\//i.test(route)) return null;
  try {
    return new URL(route, origin);
  } catch {
    return null;
  }
}
 
export function sameOriginMenuUrl(route: string, origin: string): URL | null {
  const absolute = absoluteMenuUrl(route, origin);
  return absolute?.origin === origin ? absolute : null;
}
 
function matchParamCount(menuRoute: unknown, route: CrumbRoute | null | undefined, origin?: string): number | null {
  if (!menuRoute || typeof menuRoute !== 'string') return null;
  if (!route?.fullPath || typeof route.fullPath !== 'string') return null;
  // IntelliJ может загрузить интерфейс с file URL без доступного origin.
  const portalOrigin = origin === 'null' || origin?.startsWith('file:') ? undefined : origin;
  if (!portalOrigin && HAS_SCHEME.test(menuRoute)) return null;
  const base = portalOrigin || BASE;
 
  let menuUrl: URL;
  let currentUrl: URL;
  try {
    menuUrl = new URL(menuRoute, base);
    currentUrl = new URL(route.fullPath.startsWith('/') ? base + route.fullPath : route.fullPath, base);
  } catch {
    return null;
  }
 
  // //host/docs не имеет схемы, но это чужой хост. Сравнение одних pathname приняло бы его за /docs.
  if (menuUrl.origin !== base) return null;
  if (!samePath(menuUrl.pathname, currentUrl.pathname)) return null;
 
  // Пункт меню должен указывать на ту же запись представления.
  const entity = route.distinguishEntityRecords && /^\/entities\/([^/]+)\/[^/]+\/?$/i.exec(currentUrl.pathname);
  const explicitKeys = entity && (entity[1] === 'docs' ? ['dh-doc-id', 'id'] : ['id']);
  const explicitKey = explicitKeys ? explicitKeys.find((key) => {
    const values = currentUrl.searchParams.getAll(key);
    return values.length === 1 && Boolean(values[0].trim());
  }) : undefined;
  const menuHasLegacyMarker = menuUrl.hash === SEARCH_RECORD_LINK_HASH;
  const currentHasLegacyMarker = currentUrl.hash === SEARCH_RECORD_LINK_HASH;
  const markedRecord = route.marked || (entity && currentHasLegacyMarker);
  if (markedRecord && !menuHasLegacyMarker && menuUrl.searchParams.get('_sfa-record') !== '1') return null;
  Iif (entity && menuHasLegacyMarker && !route.marked && !currentHasLegacyMarker) return null;
  const recordKey = explicitKey ?? route.recordKey;
  if (recordKey && !menuUrl.searchParams.has(recordKey)) return null;
 
  const keys = relevantKeys(menuUrl.searchParams);
  for (let i = 0; i < keys.length; i++) {
    const key = keys[i];
    Iif (markedRecord && currentHasLegacyMarker && key === '_sfa-record' &&
        menuUrl.searchParams.getAll(key).length === 1 && menuUrl.searchParams.get(key) === '1') continue;
    const expected = menuUrl.searchParams.getAll(key);
    const actual = currentUrl.searchParams.getAll(key);
    if (expected.length !== actual.length) return null;
    for (let j = 0; j < expected.length; j++) {
      if (expected[j] !== actual[j]) return null;
    }
  }
  return keys.length;
}
 
export function menuRouteMatches(menuRoute: unknown, route: CrumbRoute | null | undefined, origin?: string): boolean {
  return matchParamCount(menuRoute, route, origin) !== null;
}
 
// Самый конкретный пункт: больше совпавших query-параметров побеждает более общий.
// При равенстве остаётся тот, что раньше в датасете. Пункты без location не кандидаты.
export function findBestMenuItem(menu: readonly MenuCrumb[] | null | undefined, route: CrumbRoute | null | undefined, origin?: string): MenuCrumb | null {
  if (!Array.isArray(menu) || !route) return null;
  let best: MenuCrumb | null = null;
  let bestCount = -1;
  for (let i = 0; i < menu.length; i++) {
    const item = menu[i];
    if (!item?.location) continue;
    const count = matchParamCount(item.route, route, origin);
    if (count === null || count <= bestCount) continue;
    best = item;
    bestCount = count;
  }
  return best;
}
 
export function buildBreadcrumbs({ menu, route }: BuildBreadcrumbsArgs = {}): string[] {
  if (!route) return [];
  const item = findBestMenuItem(menu, route);
  if (!item?.location) return [];
 
  const segments = String(item.location).split('/').filter(Boolean);
  if (!segments.length) return [];
  const title = typeof item.title === 'string' ? item.title.trim() : '';
  if (title) segments[segments.length - 1] = title;
  return segments;
}
 
export interface BreadcrumbSegment {
  title: string;
  route?: string;
  current?: boolean;
  hiddenPath?: string;
}
 
export function buildBreadcrumbSegments({ menu, route, origin }: BuildBreadcrumbsArgs = {}): BreadcrumbSegment[] {
  // В дереве меню последняя запись по расположению заменяет предыдущую.
  const treeIndices = new Map<string, number>();
  const candidates: MenuCrumb[] = [];
  for (const item of menu ?? []) {
    Iif (!item?.location) continue;
    const index = item.service ? undefined : treeIndices.get(item.location);
    if (index !== undefined) {
      candidates[index] = {...item, title: item.title ?? candidates[index].title};
    } else {
      Eif (!item.service) treeIndices.set(item.location, candidates.length);
      candidates.push(item);
    }
  }
  const current = findBestMenuItem(candidates, route, origin);
  if (!current?.location) return [];
 
  const parts = current.location.split('/');
  const items = new Map(candidates.filter((item) => item?.location && Boolean(item.service) === Boolean(current.service))
    .map((item) => [item.location, item]));
  const last = parts.length - 1 - [...parts].reverse().findIndex(Boolean);
  return parts.flatMap((part, index) => {
    if (!part) return [];
    const isCurrent = index === last;
    const item = isCurrent ? current : items.get(parts.slice(0, index + 1).join('/'));
    const target = item?.route?.trim();
    const canLink = target && (!HAS_SCHEME.test(target) || /^https?:\/\//i.test(target));
    return [{
      title: item?.title?.trim() || part,
      route: !isCurrent && canLink ? target : undefined,
      current: isCurrent
    }];
  });
}
 
export function appendEntityBreadcrumb(
  previous: BreadcrumbSegment[], returnPath: string, title: string, ids: readonly string[]
): BreadcrumbSegment[] {
  const id = ids.length === 1 ? ids[0] : undefined;
  return [
    ...previous.map((crumb) => crumb.current ? { ...crumb, current: false, route: returnPath } : crumb),
    { title: title.trim() || id || 'Карточка сущности', current: true }
  ];
}
 
export function breadcrumbHiddenRange(
  widths: readonly number[], available: number, overflow: number, viewportWidth: number
): [number, number] {
  if (viewportWidth < 520) return [0, widths.length];
  let visibleWidth = widths.reduce((sum, width) => sum + width, 0);
  if (visibleWidth <= available) return [0, 0];
 
  let hidden = 0;
  while (hidden < widths.length - 1 && (hidden === 0 || visibleWidth + overflow > available)) {
    visibleWidth -= widths[hidden++];
  }
  return [0, hidden];
}
 
export function collapseBreadcrumbSegments(
  segments: BreadcrumbSegment[],
  start: number,
  end: number
): BreadcrumbSegment[] {
  if (start === end) return segments;
  const hiddenPath = segments.slice(start, end).map((segment) => segment.title).join(' / ');
  return [...segments.slice(0, start), { title: '…', hiddenPath }, ...segments.slice(end)];
}