All files / frontend/helpers markdownObjectHeader.ts

100% Statements 19/19
95.23% Branches 20/21
100% Functions 7/7
100% Lines 18/18

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                                              3x 3x                     3x   3x 3x   3x 12x     3x 8x 18x 8x 10x       3x 15x   96x 1x       96x 3x        
/*
  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.
*/
 
// Шапка объекта в markdown (Т4.6):
//   ###### Продукт                          -> надпись над заголовком
//   # Название продукта
//   `example.products.p1`                   -> идентификатор объекта
// Средствами CSS не проверить, что в абзаце нет ничего, кроме кода, и что h6 стоит именно
// перед заголовком, поэтому такие элементы помечаются классами на уровне токенов markdown-it.
 
export const OBJECT_KIND_CLASS = 'md-object-kind';
export const OBJECT_ID_CLASS = 'md-object-id';
 
// Минимальный интерфейс токена markdown-it, достаточный для разметки
interface MarkdownToken {
  type: string;
  tag: string;
  content: string;
  children: MarkdownToken[] | null;
  attrJoin(name: string, value: string): void;
}
 
const TITLE_TAGS = ['h1', 'h2'];
 
const isTitleOpen = (token?: MarkdownToken): boolean =>
  token?.type === 'heading_open' && TITLE_TAGS.includes(token.tag);
 
const isTitleClose = (token?: MarkdownToken): boolean =>
  token?.type === 'heading_close' && TITLE_TAGS.includes(token.tag);
 
// Абзац состоит только из одного inline-кода (пробелы вокруг допускаются)
const isOnlyInlineCode = (inline?: MarkdownToken): boolean => {
  const children = inline?.children || [];
  const codes = children.filter((child) => child.type === 'code_inline');
  return codes.length === 1 && children.every((child) =>
    child.type === 'code_inline' || (child.type === 'text' && !child.content.trim())
  );
};
 
export const markObjectHeader = (tokens: MarkdownToken[]): void => {
  tokens.forEach((token, index) => {
    // h6, за которым сразу идет h1/h2: heading_open(h6), inline, heading_close(h6), heading_open(h1/h2)
    if (token.type === 'heading_open' && token.tag === 'h6' && isTitleOpen(tokens[index + 3])) {
      token.attrJoin('class', OBJECT_KIND_CLASS);
    }
 
    // Абзац сразу после h1/h2, состоящий только из inline-кода
    if (token.type === 'paragraph_open' && isTitleClose(tokens[index - 1]) && isOnlyInlineCode(tokens[index + 1])) {
      token.attrJoin('class', OBJECT_ID_CLASS);
    }
  });
};