QueuedSummaryContent.tsx 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. import { type ReactNode, useEffect, useRef, useState } from "react";
  2. import { AnimatePresence, motion } from "motion/react";
  3. export const SUMMARY_ROLL_TRANSITION_MS = 300;
  4. export const SUMMARY_ROLL_HOLD_MS = 500;
  5. export const SUMMARY_ROLL_TOTAL_MS = SUMMARY_ROLL_TRANSITION_MS + SUMMARY_ROLL_HOLD_MS;
  6. const SUMMARY_ROLL_TIMER_DRIFT_SKIP_MS = 250;
  7. const SUMMARY_ROLL_MAX_PENDING = 2;
  8. const SUMMARY_ROLL_TRANSITION = {
  9. duration: SUMMARY_ROLL_TRANSITION_MS / 1000,
  10. ease: [0.4, 0, 0.2, 1],
  11. } as const;
  12. function getCurrentTimestamp() {
  13. if (typeof performance !== "undefined") {
  14. return performance.now();
  15. }
  16. return Date.now();
  17. }
  18. export function resolveQueuedSummaryPlaybackQueue<T>(
  19. queuedContent: readonly T[],
  20. timerDriftMs: number,
  21. ): T[] {
  22. if (timerDriftMs > SUMMARY_ROLL_TIMER_DRIFT_SKIP_MS && queuedContent.length > 1) {
  23. return queuedContent.slice(-1);
  24. }
  25. return [...queuedContent];
  26. }
  27. export function shouldAnimateQueuedSummaryContent({
  28. enabled,
  29. disableAnimation,
  30. reducedMotion,
  31. }: {
  32. enabled: boolean;
  33. disableAnimation?: boolean;
  34. reducedMotion: boolean;
  35. }) {
  36. return enabled && disableAnimation !== true && !reducedMotion;
  37. }
  38. interface SummaryContentSnapshot {
  39. key: string;
  40. refreshVersion?: unknown;
  41. primaryText: ReactNode;
  42. secondaryText?: ReactNode;
  43. trailingText?: ReactNode;
  44. }
  45. function usePrefersReducedMotion() {
  46. const [prefersReducedMotion, setPrefersReducedMotion] = useState(false);
  47. useEffect(() => {
  48. if (typeof window === "undefined" || typeof window.matchMedia !== "function") {
  49. return;
  50. }
  51. const query = window.matchMedia("(prefers-reduced-motion: reduce)");
  52. const update = () => {
  53. setPrefersReducedMotion(query.matches);
  54. };
  55. update();
  56. if (typeof query.addEventListener === "function") {
  57. query.addEventListener("change", update);
  58. return () => {
  59. query.removeEventListener("change", update);
  60. };
  61. }
  62. query.addListener(update);
  63. return () => {
  64. query.removeListener(update);
  65. };
  66. }, []);
  67. return prefersReducedMotion;
  68. }
  69. export function QueuedSummaryContent({
  70. contentKey,
  71. contentRefreshVersion,
  72. primaryText,
  73. secondaryText,
  74. trailingText,
  75. enabled,
  76. disableAnimation = false,
  77. }: {
  78. contentKey: string;
  79. contentRefreshVersion?: unknown;
  80. primaryText: ReactNode;
  81. secondaryText?: ReactNode;
  82. trailingText?: ReactNode;
  83. enabled: boolean;
  84. disableAnimation?: boolean;
  85. }) {
  86. const reducedMotion = usePrefersReducedMotion();
  87. const shouldAnimate = shouldAnimateQueuedSummaryContent({
  88. enabled,
  89. disableAnimation,
  90. reducedMotion,
  91. });
  92. if (!shouldAnimate) {
  93. // #185:禁用动画时逐 token 在 effect 里复制 state,会在连续同步提交中积累嵌套更新。
  94. // 静态路径直接显示输入;卸载播放 owner 同时释放旧队列,重新启用从当前内容开始。
  95. return (
  96. <>
  97. {primaryText}
  98. {secondaryText}
  99. {trailingText}
  100. </>
  101. );
  102. }
  103. return (
  104. <AnimatedSummaryContent
  105. content={{
  106. key: contentKey,
  107. refreshVersion: contentRefreshVersion,
  108. primaryText,
  109. secondaryText,
  110. trailingText,
  111. }}
  112. />
  113. );
  114. }
  115. function AnimatedSummaryContent({ content }: { content: SummaryContentSnapshot }) {
  116. const [displayedContent, setDisplayedContent] = useState(content);
  117. const displayedContentRef = useRef(content);
  118. const queuedContentRef = useRef<SummaryContentSnapshot[]>([]);
  119. const animationTimerRef = useRef<number | null>(null);
  120. const isAnimatingRef = useRef(false);
  121. useEffect(() => {
  122. const clearAnimationTimer = () => {
  123. if (animationTimerRef.current !== null) {
  124. window.clearTimeout(animationTimerRef.current);
  125. animationTimerRef.current = null;
  126. }
  127. };
  128. const enqueue = (snapshot: SummaryContentSnapshot) => {
  129. const queue = queuedContentRef.current;
  130. const existingIndex = queue.findIndex((item) => item.key === snapshot.key);
  131. if (existingIndex >= 0) {
  132. // 文件摘要正在等待播放时,持续到达的 diff 只更新同一快照,不能因为 key 去重
  133. // 留下最早的 +N/-N,也不能为每次数值变化新增整条滚动项。
  134. const nextQueue = [...queue];
  135. nextQueue[existingIndex] = snapshot;
  136. queuedContentRef.current = nextQueue;
  137. return;
  138. }
  139. if (queue.length === 0) {
  140. queuedContentRef.current = [snapshot];
  141. return;
  142. }
  143. // 摘要滚动总共只能有三格:当前显示、下一条、可插队条。
  144. // queuedContentRef 只保存后两格;第二条不能被覆盖,新摘要只能替换第三格。
  145. queuedContentRef.current = [queue[0]!, snapshot].slice(0, SUMMARY_ROLL_MAX_PENDING);
  146. };
  147. const promote = (snapshot: SummaryContentSnapshot) => {
  148. displayedContentRef.current = snapshot;
  149. setDisplayedContent(snapshot);
  150. isAnimatingRef.current = true;
  151. clearAnimationTimer();
  152. const expectedTimerAt = getCurrentTimestamp() + SUMMARY_ROLL_TOTAL_MS;
  153. animationTimerRef.current = window.setTimeout(() => {
  154. isAnimatingRef.current = false;
  155. animationTimerRef.current = null;
  156. const queuedContent = queuedContentRef.current;
  157. const timerDrift = getCurrentTimestamp() - expectedTimerAt;
  158. // 主线程繁忙时 timeout 会晚到;如果继续逐条补播旧摘要,
  159. // 用户会在卡顿恢复后看到过期状态排队播放,体感上会更卡。
  160. const nextQueue = resolveQueuedSummaryPlaybackQueue(queuedContent, timerDrift);
  161. const [nextQueued, ...restQueued] = nextQueue;
  162. if (!nextQueued) {
  163. queuedContentRef.current = [];
  164. return;
  165. }
  166. queuedContentRef.current = restQueued;
  167. promote(nextQueued);
  168. }, SUMMARY_ROLL_TOTAL_MS);
  169. };
  170. const nextContent = content;
  171. if (displayedContentRef.current.key === nextContent.key) {
  172. // 同一摘要的正文与计数直接由输入派生,不能再 setState;外层组头也会逐 token 更新。
  173. // 仅在提交后保存最后显示的快照,下一项排队时仍能冻结当前项的最新内容。
  174. displayedContentRef.current = nextContent;
  175. return;
  176. }
  177. if (isAnimatingRef.current) {
  178. enqueue(nextContent);
  179. return;
  180. }
  181. if (queuedContentRef.current.length > 0) {
  182. enqueue(nextContent);
  183. return;
  184. }
  185. promote(nextContent);
  186. }, [content]);
  187. useEffect(() => {
  188. return () => {
  189. if (animationTimerRef.current !== null) {
  190. window.clearTimeout(animationTimerRef.current);
  191. }
  192. };
  193. }, []);
  194. // state 只推进播放项;ref 保存该项的最新已提交输入,不在 render 中写入。
  195. const renderedContent =
  196. content.key === displayedContent.key ? content : displayedContentRef.current;
  197. return (
  198. <span className="relative inline-flex min-w-0 items-center gap-2 overflow-hidden align-middle">
  199. <AnimatePresence initial={false} mode="popLayout">
  200. <motion.span
  201. key={renderedContent.key}
  202. className="inline-flex min-w-0 items-center gap-2"
  203. initial={{ y: "0.8em", opacity: 0 }}
  204. animate={{ y: 0, opacity: 1 }}
  205. exit={{ y: "-0.8em", opacity: 0 }}
  206. transition={SUMMARY_ROLL_TRANSITION}
  207. >
  208. {renderedContent.primaryText}
  209. {renderedContent.secondaryText}
  210. </motion.span>
  211. </AnimatePresence>
  212. {/* 修复原因:Changes 的 diff count 必须与文件摘要属于同一排队快照,
  213. 但数字自身继续用 FlipMetricValue 独立翻动,不能跟整条摘要一起纵向滚走。 */}
  214. {renderedContent.trailingText}
  215. </span>
  216. );
  217. }