useActivePath.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { useMemo, useCallback } from "react";
  2. import type { MessageNode } from "../types/chat"
  3. export function useActivePath(
  4. rawMessages: MessageNode[],
  5. activePoint?: string
  6. ) {
  7. const computeActivePath = useCallback(() => {
  8. // 从root消息开始,最新消息的路径构建激活链
  9. console.debug("ai chat", rawMessages);
  10. const activePath: MessageNode[] = [];
  11. // 找到system消息(根节点)
  12. let rootMsg = rawMessages.find((m) => !m.parent_id);
  13. if (!rootMsg) return [];
  14. if (activePoint) {
  15. //向上
  16. const activeMsg = rawMessages.find((v) => v.uid === activePoint);
  17. if (!activeMsg) {
  18. return [];
  19. }
  20. let currParent: MessageNode | undefined = rawMessages.find(
  21. (m) => m.uid === activeMsg.parent_id
  22. );
  23. while (currParent) {
  24. const pId = currParent.parent_id;
  25. activePath.unshift(currParent);
  26. currParent = rawMessages.find((v) => v.uid === pId);
  27. }
  28. rootMsg = activeMsg;
  29. }
  30. let current: MessageNode | undefined = rootMsg;
  31. while (current) {
  32. const currId: string = current.uid;
  33. activePath.push(current);
  34. // 找到当前消息的激活子消息
  35. current = rawMessages.filter((value) => value.parent_id === currId).pop();
  36. }
  37. return activePath;
  38. }, [activePoint, rawMessages]);
  39. return useMemo(() => computeActivePath(), [computeActivePath]);
  40. }