searchShowRed.ets 2.21 KB
import { Logger } from "wdKit";

export interface textItem {
  content: string,
  isRed: boolean
}

export interface titleInitRes  {
  titleMarked: boolean,
  textArr: textItem[]
}

const TAG = "SearchShowRed"

export class SearchShowRed {
  // title: this.contentDTO.title
  static titleInit(title: string) {
    let titleMarked: boolean = false;
    let textArr: textItem[] = [];

    if (title?.includes('<em>') && title?.includes('</em>')) {
      titleMarked = true;

      const html: string = title;
      const pattern = /<[a-z]+[1-6]?\b[^>]*>(.*?)<\/[a-z]+[1-6]?>/g;
      const res: string[] = [];
      let match: RegExpExecArray | null;

      while ((match = pattern.exec(html)) !== null) {
        const content: string = match[1].trim();
        res.push(content);
      }

      Logger.debugOptimize(TAG, () => {
        return 'SearchShowRed-res' + JSON.stringify(res)
      })

      SearchShowRed.formatTitle(
        html.replaceAll('<em>', '').replaceAll('</em>', ''),
        res,
        0,
        textArr
      );
    }

    const titleInitRes: titleInitRes = {
      titleMarked,
      textArr
    }
    Logger.debugOptimize(TAG, () => {
      return 'SearchShowRed-titleInitRes ' + JSON.stringify(titleInitRes)
    })
    return titleInitRes
  }

  private static formatTitle(textStr: string, matchArr: string[], index: number, textArr: textItem[]) {
    const item: string = matchArr[index];
    if (!item) {
      textArr.push({
        content: textStr,
        isRed: false
      })
      return;
    }
    const ind = textStr.indexOf(item);
    const len = item.length;
    if (ind === 0) {
      textArr.push({
        content: item,
        isRed: true
      })
      SearchShowRed.formatTitle(textStr.slice(len), matchArr, index + 1, textArr);
    } else if (ind + len === textStr.length) {
      textArr.push({
        content: textStr.slice(0, ind),
        isRed: false
      })
      textArr.push({
        content: item,
        isRed: true
      })
    } else {
      textArr.push({
        content: textStr.slice(0, ind),
        isRed: false
      })
      textArr.push({
        content: item,
        isRed: true
      })
      SearchShowRed.formatTitle(textStr.slice(ind + len), matchArr, index + 1, textArr);
    }
  }
}