Files
PaperClipAI/ui/src/hooks/useOnboardingReplyDisplay.ts
T

99 lines
4.6 KiB
TypeScript

import { useEffect, useRef } from "react";
import type { IssueComment, IssueThreadInteraction } from "@paperclipai/shared";
import type { RunForIssue } from "@/api/activity";
import { captureProductAnalyticsEvent, hasCapturedProductEvent } from "@/lib/analytics/product-analytics";
type ChatInput = Pick<IssueComment, "id" | "issueId" | "authorType" | "authorUserId" | "deletedAt" | "createdByRunId">;
function replyInputs(userId: string, chatId: string, runs: readonly RunForIssue[], comments: readonly ChatInput[],
welcomeChoice?: IssueThreadInteraction) {
const own = new Set(comments.filter(comment =>
comment.issueId === chatId && comment.authorType === "user" && comment.authorUserId === userId
&& !comment.deletedAt && !comment.createdByRunId,
).map(comment => comment.id));
if (welcomeChoice?.issueId === chatId && welcomeChoice.status === "answered" && welcomeChoice.resolvedByUserId === userId) {
own.add(welcomeChoice.id);
}
const inputs = new Map<string, string>();
for (const run of runs) {
const messageId = run.triggeringChatInputId;
if (run.contextIssueId === chatId && messageId && own.has(messageId)) {
inputs.set(run.runId, messageId);
}
}
return inputs;
}
function visibleReplyText(body: HTMLElement, viewport: HTMLElement) {
if (body.closest("[inert], [aria-hidden=true]")) return false;
if (body.checkVisibility && !body.checkVisibility({ opacityProperty: true, visibilityProperty: true })) return false;
const bounds = viewport.getBoundingClientRect();
const walker = document.createTreeWalker(body, NodeFilter.SHOW_TEXT);
const range = document.createRange();
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
const element = node.parentElement;
if (!node.textContent?.trim() || !element || element.closest("button, [aria-hidden=true]")) continue;
range.selectNodeContents(node);
for (const rect of range.getClientRects()) {
const left = Math.max(0, rect.left, bounds.left);
const right = Math.min(innerWidth, rect.right, bounds.right);
const top = Math.max(0, rect.top, bounds.top);
const bottom = Math.min(innerHeight, rect.bottom, bounds.bottom);
if (right > left && bottom > top && element.contains(document.elementFromPoint((left + right) / 2, (top + bottom) / 2))) {
return true;
}
}
}
return false;
}
export function useOnboardingReplyDisplay(
userId: string | undefined, chatId: string, runs: readonly RunForIssue[],
comments: readonly ChatInput[], welcomeChoice?: IssueThreadInteraction,
) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const thread = ref.current;
if (!thread || !userId) return;
const onceKey = `paperclip:first-chat-reply:${userId}:${chatId}`;
if (hasCapturedProductEvent(onceKey)) return;
const inputs = replyInputs(userId, chatId, runs, comments, welcomeChoice);
if (!inputs.size) return;
const listeners = new AbortController();
const options = { signal: listeners.signal, capture: true };
let frame = 0;
const check = () => {
frame = 0;
if (document.visibilityState !== "visible" || !document.hasFocus()) return;
for (const reply of thread.querySelectorAll<HTMLElement>("[data-reply-run]")) {
const messageId = inputs.get(reply.dataset.replyRun!);
const body = reply.querySelector<HTMLElement>(":scope > .paperclip-markdown");
const viewport = reply.closest<HTMLElement>(".task-chat-scroll-viewport");
if (!messageId || !body || !viewport || !visibleReplyText(body, viewport)) continue;
captureProductAnalyticsEvent("agent_chat_reply_displayed", {
surface: "onboarding_chat", reply_kind: "response_to_user", chat_id: chatId, message_id: messageId,
}, { userId, onceKey });
stop();
break;
}
};
const schedule = () => { if (!frame) frame = requestAnimationFrame(check); };
const observer = new MutationObserver(schedule);
observer.observe(thread, { subtree: true, childList: true, characterData: true, attributes: true,
attributeFilter: ["data-reply-run", "inert", "class", "style", "aria-hidden"] });
const size = new ResizeObserver(schedule);
size.observe(thread);
for (const event of ["scroll", "resize", "load", "focus", "animationend", "transitionend"]) window.addEventListener(event, schedule, options);
document.addEventListener("visibilitychange", schedule, options);
function stop() {
observer.disconnect();
size.disconnect();
listeners.abort();
cancelAnimationFrame(frame);
}
schedule();
return stop;
}, [userId, chatId, runs, comments, welcomeChoice]);
return ref;
}