Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { Task } from "@posthog/shared/domain-types";
import { Theme } from "@radix-ui/themes";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import { TaskFeedRow } from "./ChannelFeedView";

const task = {
Expand All @@ -24,22 +24,60 @@ const task = {
} satisfies Task;

describe("TaskFeedRow", () => {
afterEach(() => {
vi.restoreAllMocks();
});

it("expands a truncated prompt", async () => {
vi.spyOn(HTMLElement.prototype, "scrollHeight", "get").mockReturnValue(60);
vi.spyOn(HTMLElement.prototype, "scrollHeight", "get").mockImplementation(
function (this: HTMLElement) {
return (this.textContent?.length ?? 0) > 35 ? 60 : 20;
},
);
vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockReturnValue(40);
const user = userEvent.setup();
render(
const { container } = render(
<Theme>
<TaskFeedRow task={task} />
</Theme>,
);

const prompt = screen.getByText(task.description);
expect(prompt).toHaveClass("line-clamp-2");
const prompt = container.querySelector(
'[data-slot="thread-item-body"]:not([aria-hidden])',
);
const more = screen.getByRole("button", { name: "more" });
expect(prompt).toHaveTextContent(/\.\.\. more$/);
expect(prompt).toContainElement(more);

await user.click(screen.getByRole("button", { name: "more" }));
await user.click(more);

expect(prompt).not.toHaveClass("line-clamp-2");
expect(prompt).toHaveTextContent(task.description);
expect(screen.getByRole("button", { name: "less" })).toBeInTheDocument();
});

it("collapses newlines and whitespace before truncating", () => {
vi.spyOn(HTMLElement.prototype, "scrollHeight", "get").mockImplementation(
function (this: HTMLElement) {
return (this.textContent?.length ?? 0) > 35 ? 60 : 20;
},
);
vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockReturnValue(40);
const multilineTask = {
...task,
description:
"truncation was recently added to message prompts, but\n\nthere is more text after it",
};

const { container } = render(
<Theme>
<TaskFeedRow task={multilineTask} />
</Theme>,
);

const prompt = container.querySelector(
'[data-slot="thread-item-body"]:not([aria-hidden])',
);
expect(prompt?.textContent).not.toContain("\n");
expect(prompt).toHaveTextContent(/[^ ]\.\.\. more$/);
});
});
78 changes: 58 additions & 20 deletions packages/ui/src/features/canvas/components/ChannelFeedView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -422,42 +422,80 @@ function ExpandablePrompt({
}) {
const observerRef = useRef<ResizeObserver | null>(null);
const [expanded, setExpanded] = useState(false);
const [truncated, setTruncated] = useState(false);
const [truncatedText, setTruncatedText] = useState<string | null>(null);
const measureTextRef = useRef<HTMLSpanElement>(null);
const measureMoreRef = useRef<HTMLSpanElement>(null);
const collapsedText = children.replace(/\s+/g, " ").trim();

const measureRef = useCallback(
(body: HTMLDivElement | null) => {
observerRef.current?.disconnect();
observerRef.current = null;
if (!body || expanded) return;
const measure = () => setTruncated(body.scrollHeight > body.clientHeight);
const measure = () => {
const text = measureTextRef.current;
const more = measureMoreRef.current;
if (!text || !more) return;

more.hidden = true;
text.textContent = collapsedText;
if (body.scrollHeight <= body.clientHeight) {
setTruncatedText(null);
return;
}

more.hidden = false;
let low = 0;
let high = collapsedText.length;
while (low < high) {
const middle = Math.ceil((low + high) / 2);
text.textContent = `${collapsedText.slice(0, middle).trimEnd()}... `;
if (body.scrollHeight <= body.clientHeight) {
low = middle;
} else {
high = middle - 1;
}
}
setTruncatedText(collapsedText.slice(0, low).trimEnd());
Comment on lines +448 to +459

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Unicode Boundary Corrupts Prompt Text

The search slices by UTF-16 code units. When the fitting boundary lands inside a supplementary character such as an emoji, the collapsed prompt renders a replacement glyph before the ellipsis.

Suggested change
let low = 0;
let high = collapsedText.length;
while (low < high) {
const middle = Math.ceil((low + high) / 2);
text.textContent = `${collapsedText.slice(0, middle).trimEnd()}... `;
if (body.scrollHeight <= body.clientHeight) {
low = middle;
} else {
high = middle - 1;
}
}
setTruncatedText(collapsedText.slice(0, low).trimEnd());
const collapsedCharacters = Array.from(collapsedText);
let low = 0;
let high = collapsedCharacters.length;
while (low < high) {
const middle = Math.ceil((low + high) / 2);
text.textContent = `${collapsedCharacters.slice(0, middle).join("").trimEnd()}... `;
if (body.scrollHeight <= body.clientHeight) {
low = middle;
} else {
high = middle - 1;
}
}
setTruncatedText(
collapsedCharacters.slice(0, low).join("").trimEnd(),
);
Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/ui/src/features/canvas/components/ChannelFeedView.tsx
Line: 448-459

Comment:
**Unicode Boundary Corrupts Prompt Text**

The search slices by UTF-16 code units. When the fitting boundary lands inside a supplementary character such as an emoji, the collapsed prompt renders a replacement glyph before the ellipsis.

```suggestion
        const collapsedCharacters = Array.from(collapsedText);
        let low = 0;
        let high = collapsedCharacters.length;
        while (low < high) {
          const middle = Math.ceil((low + high) / 2);
          text.textContent = `${collapsedCharacters.slice(0, middle).join("").trimEnd()}... `;
          if (body.scrollHeight <= body.clientHeight) {
            low = middle;
          } else {
            high = middle - 1;
          }
        }
        setTruncatedText(
          collapsedCharacters.slice(0, low).join("").trimEnd(),
        );
```

How can I resolve this? If you propose a fix, please make it concise.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

};
measure();
const observer = new ResizeObserver(measure);
observer.observe(body);
observer.observe(body.parentElement ?? body);
observerRef.current = observer;
},
[expanded],
[collapsedText, expanded],
);

return (
<div>
<ThreadItemBody
ref={measureRef}
className={cn(
"wrap-break-word whitespace-pre-wrap",
!expanded && (lines === 2 ? "line-clamp-2" : "line-clamp-4"),
<div className="relative">
<ThreadItemBody className="wrap-break-word whitespace-pre-wrap">
{expanded || truncatedText === null ? children : truncatedText}
{truncatedText !== null && !expanded && "... "}
{truncatedText !== null && (
Comment on lines +473 to +474

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Expanded Action Joins Final Word

The expanded branch renders the original prompt directly beside the less button. When the prompt does not end with whitespace, users see text such as final wordless instead of a separated inline action.

Suggested change
{truncatedText !== null && !expanded && "... "}
{truncatedText !== null && (
{truncatedText !== null && (expanded ? " " : "... ")}
{truncatedText !== null && (

Rule Used: Maintain proper spacing in template strings. Ensur... (source)

Learned From
PostHog/posthog#32603

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/ui/src/features/canvas/components/ChannelFeedView.tsx
Line: 473-474

Comment:
**Expanded Action Joins Final Word**

The expanded branch renders the original prompt directly beside the `less` button. When the prompt does not end with whitespace, users see text such as `final wordless` instead of a separated inline action.

```suggestion
        {truncatedText !== null && (expanded ? " " : "... ")}
        {truncatedText !== null && (
```

**Rule Used:** Maintain proper spacing in template strings. Ensur... ([source](https://app.greptile.com/posthog-org-19734/-/custom-context?memory=d0a97985-7ddb-464d-9739-625899016a97))

**Learned From**
[PostHog/posthog#32603](https://github.com/PostHog/posthog/pull/32603)

How can I resolve this? If you propose a fix, please make it concise.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

<button
type="button"
aria-expanded={expanded}
className="text-muted-foreground text-xs underline underline-offset-2 hover:text-foreground"
onClick={() => setExpanded((value) => !value)}
>
{expanded ? "less" : "more"}
</button>
)}
>
{children}
</ThreadItemBody>
{(truncated || expanded) && (
<button
type="button"
aria-expanded={expanded}
className="text-muted-foreground text-xs underline underline-offset-2 hover:text-foreground"
onClick={() => setExpanded((value) => !value)}
{!expanded && (
<ThreadItemBody
ref={measureRef}
aria-hidden="true"
className={cn(
"wrap-break-word pointer-events-none invisible absolute inset-x-0 top-0 whitespace-normal",
lines === 2 ? "line-clamp-2" : "line-clamp-4",
)}
>
{expanded ? "less" : "more"}
</button>
<span ref={measureTextRef}>{collapsedText}</span>
<span ref={measureMoreRef} className="text-xs">
more
</span>
</ThreadItemBody>
)}
</div>
);
Expand Down
Loading