searchDemo.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. const fs = require("fs");
  2. const readline = require("readline");
  3. function search(str) {
  4. const locale = "zh-CN";
  5. const { nodeMap, mdxInfoList } = JSON.parse(fs.readFileSync("data_client.json"))[locale];
  6. //搜索正文
  7. const getContext = (node) => {
  8. let context = [];
  9. while (node.parent) {
  10. context.push(nodeMap[node.parent].value);
  11. node = nodeMap[node.parent];
  12. }
  13. return context.reverse();
  14. };
  15. const resultNodeList = Object.entries(nodeMap)
  16. .map(([_, value]) => value)
  17. .filter((node) => {
  18. if (node.type === "jsx") return false;
  19. return node.value.indexOf(str) !== -1;
  20. });
  21. let resultList = [];
  22. resultNodeList.map((node) => {
  23. const result = {
  24. text: node.value,
  25. type: node.meaningfulType,
  26. context: getContext(node).join(" => "),
  27. url: "https://semi.design/design/" + node.mdxInfo.slug + (node.anchor ? node.anchor : nodeMap[node.parent].anchor),
  28. };
  29. resultList.push(result);
  30. });
  31. //搜索mdx yaml (标题+brief)
  32. const resultMdxInfoList = mdxInfoList.filter((mdxInfo) => mdxInfo.title.indexOf(str) !== -1 || (mdxInfo.brief&&mdxInfo.brief.indexOf(str) !== -1));
  33. resultList = resultList.concat(
  34. resultMdxInfoList.map((mdxInfo) => {
  35. const keyInTitleOrBrief = mdxInfo.title.indexOf(str) !== -1 ? "title" : "brief";
  36. return {
  37. text: mdxInfo[keyInTitleOrBrief],
  38. type: keyInTitleOrBrief,
  39. url: "https://semi.design/design/" + mdxInfo.slug,
  40. };
  41. })
  42. );
  43. return resultList;
  44. }
  45. function readSyncByRl(tips) {
  46. tips = tips || "> ";
  47. return new Promise((resolve) => {
  48. const rl = readline.createInterface({
  49. input: process.stdin,
  50. output: process.stdout,
  51. });
  52. rl.question(tips, (answer) => {
  53. rl.close();
  54. resolve(answer.trim());
  55. });
  56. });
  57. }
  58. readSyncByRl("请输入搜索关键词:").then((res) => {
  59. search(res);
  60. });