Skip to content

Commit 58801e5

Browse files
ziyadevhaydenbleaselclaude
authored
feat(prompt-input): add screenshot action to the prompt input (#382)
* feat(prompt-input): add screenshot action with tests and docs * fix: rename ScreenShoot to Screenshot, add own props type, fix quotes and formatting - Fix typo: PromptInputActionAddScreenShoot → PromptInputActionAddScreenshot - Add dedicated PromptInputActionAddScreenshotProps type - Replace console.error with throw for unexpected errors - Fix single quotes to double quotes for consistency - Restore trailing comma on XIcon import - Add missing blank line before comment block - Add patch changeset Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Hayden Bleasel <hello@haydenbleasel.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
1 parent d1bd5f8 commit 58801e5

6 files changed

Lines changed: 301 additions & 0 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"ai-elements": patch
3+
---
4+
5+
Add PromptInputActionAddScreenshot component for capturing screenshots via getDisplayMedia

‎apps/docs/content/components/(chatbot)/prompt-input.mdx‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import {
3030
import {
3131
PromptInput,
3232
PromptInputActionAddAttachments,
33+
PromptInputActionAddScreenshot,
3334
PromptInputActionMenu,
3435
PromptInputActionMenuContent,
3536
PromptInputActionMenuTrigger,
@@ -168,6 +169,7 @@ const InputDemo = () => {
168169
<PromptInputActionMenuTrigger />
169170
<PromptInputActionMenuContent>
170171
<PromptInputActionAddAttachments />
172+
<PromptInputActionAddScreenshot />
171173
</PromptInputActionMenuContent>
172174
</PromptInputActionMenu>
173175
<PromptInputButton
@@ -239,6 +241,7 @@ export async function POST(req: Request) {
239241

240242
- Auto-resizing textarea that adjusts height based on content
241243
- File attachment support with drag-and-drop
244+
- Built-in screenshot capture action
242245
- Image preview for image attachments
243246
- Configurable file constraints (max files, max size, accepted types)
244247
- Automatic submit button icons based on status
@@ -542,6 +545,23 @@ Attachment components have been moved to a separate module. See the [Attachment]
542545
}}
543546
/>
544547

548+
### `<PromptInputActionAddScreenshot />`
549+
550+
<TypeTable
551+
type={{
552+
label: {
553+
description: "Label for the menu item.",
554+
type: "string",
555+
default: '"Take screenshot"',
556+
},
557+
"...props": {
558+
description:
559+
"Any other props are spread to the underlying DropdownMenuItem component.",
560+
type: "React.ComponentProps<typeof DropdownMenuItem>",
561+
},
562+
}}
563+
/>
564+
545565
### `<PromptInputProvider />`
546566

547567
<TypeTable

‎packages/elements/__tests__/prompt-input.test.tsx‎

Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
import {
1717
PromptInput,
1818
PromptInputActionAddAttachments,
19+
PromptInputActionAddScreenshot,
1920
PromptInputActionMenu,
2021
PromptInputActionMenuContent,
2122
PromptInputActionMenuItem,
@@ -159,6 +160,84 @@ const setupPromptInputTests = () => {
159160
}) as unknown as typeof FileReader;
160161
};
161162

163+
const setupScreenshotCaptureMock = () => {
164+
if (!navigator.mediaDevices) {
165+
Object.defineProperty(navigator, "mediaDevices", {
166+
configurable: true,
167+
value: {},
168+
writable: true,
169+
});
170+
}
171+
172+
if (!("getDisplayMedia" in navigator.mediaDevices)) {
173+
Object.defineProperty(navigator.mediaDevices, "getDisplayMedia", {
174+
configurable: true,
175+
value: vi.fn(),
176+
writable: true,
177+
});
178+
}
179+
180+
const stopTrack = vi.fn();
181+
const stream = {
182+
getTracks: () => [{ stop: stopTrack }],
183+
} as unknown as MediaStream;
184+
185+
const getDisplayMedia = vi
186+
.spyOn(navigator.mediaDevices, "getDisplayMedia")
187+
.mockResolvedValue(stream);
188+
189+
const originalCreateElement = document.createElement.bind(document);
190+
const video = originalCreateElement("video");
191+
const canvas = originalCreateElement("canvas");
192+
const drawImage = vi.fn();
193+
const play = vi.spyOn(video, "play").mockResolvedValue();
194+
const pause = vi.spyOn(video, "pause").mockImplementation(vi.fn());
195+
196+
Object.defineProperty(video, "videoWidth", {
197+
configurable: true,
198+
value: 1280,
199+
});
200+
Object.defineProperty(video, "videoHeight", {
201+
configurable: true,
202+
value: 720,
203+
});
204+
205+
let srcObject: unknown = null;
206+
Object.defineProperty(video, "srcObject", {
207+
configurable: true,
208+
get: () => srcObject,
209+
set: (value) => {
210+
srcObject = value;
211+
if (value) {
212+
setTimeout(() => {
213+
video.onloadedmetadata?.(new Event("loadedmetadata"));
214+
}, 0);
215+
}
216+
},
217+
});
218+
219+
vi.spyOn(canvas, "getContext").mockReturnValue({
220+
drawImage,
221+
} as unknown as CanvasRenderingContext2D);
222+
// oxlint-disable-next-line eslint-plugin-promise(prefer-await-to-callbacks)
223+
const toBlob = vi.spyOn(canvas, "toBlob").mockImplementation((callback) => {
224+
// oxlint-disable-next-line eslint-plugin-promise(prefer-await-to-callbacks)
225+
callback?.(new Blob(["mock-screenshot"], { type: "image/png" }));
226+
});
227+
228+
vi.spyOn(document, "createElement").mockImplementation(((tagName: string) => {
229+
if (tagName === "video") {
230+
return video;
231+
}
232+
if (tagName === "canvas") {
233+
return canvas;
234+
}
235+
return originalCreateElement(tagName as keyof HTMLElementTagNameMap);
236+
}) as typeof document.createElement);
237+
238+
return { getDisplayMedia, pause, play, stopTrack, toBlob };
239+
};
240+
162241
describe("promptInput", () => {
163242
it("renders form", () => {
164243
setupPromptInputTests();
@@ -2712,6 +2791,86 @@ describe("promptInputActionAddAttachments", () => {
27122791
});
27132792
});
27142793

2794+
describe("promptInputActionAddScreenshot", () => {
2795+
it("captures a screenshot and adds it as attachment", async () => {
2796+
setupPromptInputTests();
2797+
const onSubmit = vi.fn();
2798+
const user = userEvent.setup();
2799+
const { getDisplayMedia, pause, play, stopTrack, toBlob } =
2800+
setupScreenshotCaptureMock();
2801+
2802+
render(
2803+
<PromptInput onSubmit={onSubmit}>
2804+
<PromptInputBody>
2805+
<PromptInputAttachments>
2806+
{(attachment) => (
2807+
<div key={attachment.id}>{attachment.filename}</div>
2808+
)}
2809+
</PromptInputAttachments>
2810+
<PromptInputActionMenu>
2811+
<PromptInputActionMenuTrigger />
2812+
<PromptInputActionMenuContent>
2813+
<PromptInputActionAddScreenshot />
2814+
</PromptInputActionMenuContent>
2815+
</PromptInputActionMenu>
2816+
<PromptInputTextarea />
2817+
</PromptInputBody>
2818+
</PromptInput>
2819+
);
2820+
2821+
await user.click(screen.getByRole("button"));
2822+
await user.click(screen.getByText("Take screenshot"));
2823+
2824+
await vi.waitFor(() => {
2825+
expect(screen.getByText(/^screenshot-.*\.png$/)).toBeInTheDocument();
2826+
});
2827+
expect(getDisplayMedia).toHaveBeenCalledOnce();
2828+
expect(play).toHaveBeenCalledOnce();
2829+
expect(toBlob).toHaveBeenCalledOnce();
2830+
expect(stopTrack).toHaveBeenCalledOnce();
2831+
expect(pause).toHaveBeenCalledOnce();
2832+
});
2833+
2834+
it("ignores denied capture permission", async () => {
2835+
setupPromptInputTests();
2836+
const onSubmit = vi.fn();
2837+
const user = userEvent.setup();
2838+
const consoleError = vi.spyOn(console, "error").mockImplementation(vi.fn());
2839+
const { getDisplayMedia } = setupScreenshotCaptureMock();
2840+
getDisplayMedia.mockRejectedValue(
2841+
new DOMException("Permission denied", "NotAllowedError")
2842+
);
2843+
2844+
render(
2845+
<PromptInput onSubmit={onSubmit}>
2846+
<PromptInputBody>
2847+
<PromptInputAttachments>
2848+
{(attachment) => (
2849+
<div key={attachment.id}>{attachment.filename}</div>
2850+
)}
2851+
</PromptInputAttachments>
2852+
<PromptInputActionMenu>
2853+
<PromptInputActionMenuTrigger />
2854+
<PromptInputActionMenuContent>
2855+
<PromptInputActionAddScreenshot />
2856+
</PromptInputActionMenuContent>
2857+
</PromptInputActionMenu>
2858+
<PromptInputTextarea />
2859+
</PromptInputBody>
2860+
</PromptInput>
2861+
);
2862+
2863+
await user.click(screen.getByRole("button"));
2864+
await user.click(screen.getByText("Take screenshot"));
2865+
2866+
await vi.waitFor(() => {
2867+
expect(getDisplayMedia).toHaveBeenCalledOnce();
2868+
});
2869+
expect(screen.queryByText(/^screenshot-.*\.png$/)).not.toBeInTheDocument();
2870+
expect(consoleError).not.toHaveBeenCalled();
2871+
});
2872+
});
2873+
27152874
describe("promptInputHeader", () => {
27162875
it("renders header content", async () => {
27172876
setupPromptInputTests();

‎packages/elements/src/prompt-input.tsx‎

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ import { cn } from "@repo/shadcn-ui/lib/utils";
5858
import {
5959
CornerDownLeftIcon,
6060
ImageIcon,
61+
Monitor,
6162
PlusIcon,
6263
SquareIcon,
6364
XIcon,
@@ -97,6 +98,73 @@ const convertBlobUrlToDataUrl = async (url: string): Promise<string | null> => {
9798
}
9899
};
99100

101+
const captureScreenshot = async (): Promise<File | null> => {
102+
if (
103+
typeof navigator === "undefined" ||
104+
!navigator.mediaDevices?.getDisplayMedia
105+
) {
106+
return null;
107+
}
108+
109+
let stream: MediaStream | null = null;
110+
const video = document.createElement("video");
111+
video.muted = true;
112+
video.playsInline = true;
113+
114+
try {
115+
stream = await navigator.mediaDevices.getDisplayMedia({
116+
audio: false,
117+
video: true,
118+
});
119+
120+
video.srcObject = stream;
121+
122+
await new Promise<void>((resolve, reject) => {
123+
video.onloadedmetadata = () => resolve();
124+
video.onerror = () => reject(new Error("Failed to load screen stream"));
125+
});
126+
127+
await video.play();
128+
129+
const width = video.videoWidth;
130+
const height = video.videoHeight;
131+
if (!width || !height) {
132+
return null;
133+
}
134+
135+
const canvas = document.createElement("canvas");
136+
canvas.width = width;
137+
canvas.height = height;
138+
const context = canvas.getContext("2d");
139+
if (!context) {
140+
return null;
141+
}
142+
143+
context.drawImage(video, 0, 0, width, height);
144+
const blob = await new Promise<Blob | null>((resolve) =>
145+
canvas.toBlob(resolve, "image/png")
146+
);
147+
if (!blob) {
148+
return null;
149+
}
150+
151+
const timestamp = new Date()
152+
.toISOString()
153+
.replaceAll(/[:.]/g, "-")
154+
.replace("T", "_")
155+
.replace("Z", "");
156+
157+
return new File([blob], `screenshot-${timestamp}.png`, {
158+
lastModified: Date.now(),
159+
type: "image/png",
160+
});
161+
} finally {
162+
stream?.getTracks().forEach((track) => track.stop());
163+
video.pause();
164+
video.srcObject = null;
165+
}
166+
};
167+
100168
// ============================================================================
101169
// Provider Context & Types
102170
// ============================================================================
@@ -358,6 +426,50 @@ export const PromptInputActionAddAttachments = ({
358426
);
359427
};
360428

429+
export type PromptInputActionAddScreenshotProps = ComponentProps<
430+
typeof DropdownMenuItem
431+
> & {
432+
label?: string;
433+
};
434+
435+
export const PromptInputActionAddScreenshot = ({
436+
label = "Take screenshot",
437+
onSelect,
438+
...props
439+
}: PromptInputActionAddScreenshotProps) => {
440+
const attachments = usePromptInputAttachments();
441+
442+
return (
443+
<DropdownMenuItem
444+
{...props}
445+
onSelect={async (event) => {
446+
onSelect?.(event);
447+
if (event.defaultPrevented) {
448+
return;
449+
}
450+
451+
try {
452+
const screenshot = await captureScreenshot();
453+
if (screenshot) {
454+
attachments.add([screenshot]);
455+
}
456+
} catch (error) {
457+
if (
458+
error instanceof DOMException &&
459+
(error.name === "NotAllowedError" || error.name === "AbortError")
460+
) {
461+
return;
462+
}
463+
throw error;
464+
}
465+
}}
466+
>
467+
<Monitor className="mr-2 size-4" />
468+
{label}
469+
</DropdownMenuItem>
470+
);
471+
};
472+
361473
export interface PromptInputMessage {
362474
text: string;
363475
files: FileUIPart[];

‎packages/examples/src/prompt-input.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import {
2424
import {
2525
PromptInput,
2626
PromptInputActionAddAttachments,
27+
PromptInputActionAddScreenshot,
2728
PromptInputActionMenu,
2829
PromptInputActionMenuContent,
2930
PromptInputActionMenuTrigger,
@@ -209,6 +210,7 @@ const Example = () => {
209210
<PromptInputActionMenuTrigger />
210211
<PromptInputActionMenuContent>
211212
<PromptInputActionAddAttachments />
213+
<PromptInputActionAddScreenshot />
212214
</PromptInputActionMenuContent>
213215
</PromptInputActionMenu>
214216
<PromptInputButton>

0 commit comments

Comments
 (0)