utils.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. export const SCENE_URL = window.location.pathname.replace(
  2. /\/(pc|mobile)\/index.html$/,
  3. "/scene/syjy.html?m=SG-SkJEj1Vhf7l"
  4. );
  5. export const extractText = (html) => {
  6. // 提取纯文本,去掉HTML标签
  7. const tmpDiv = document.createElement("div");
  8. tmpDiv.innerHTML = html;
  9. return tmpDiv.innerText.trim();
  10. };
  11. export const findKeywordContext = (text, keyword, radius = 20) => {
  12. const index = text.indexOf(keyword);
  13. if (index === -1) {
  14. return null;
  15. }
  16. const start = Math.max(0, index - radius);
  17. const end = Math.min(text.length, index + keyword.length + radius);
  18. return text.substring(start, end);
  19. };
  20. export const flattenData = (query, list, parentTitles = [], path = []) => {
  21. const result = [];
  22. list.forEach((item, index) => {
  23. const titles = [...parentTitles, item.title];
  24. const currentPath = [...path, index];
  25. if (item.content) {
  26. const contentText = extractText(item.content).replace(/[\n\s]/g, "");
  27. if (contentText.indexOf(query) > -1) {
  28. result.push({
  29. value: currentPath.join(","),
  30. label: `${titles.join(" | ")} | ${findKeywordContext(
  31. contentText,
  32. query
  33. )}`,
  34. });
  35. }
  36. }
  37. if (item.children) {
  38. result.push(...flattenData(query, item.children, titles, currentPath));
  39. }
  40. });
  41. return result;
  42. };