Open History to see the last commit
1import type { PickedElementPayload } from "@t3tools/contracts";
2import { describe, expect, it } from "vite-plus/test";
3
4import {
5 appendElementContextsToPrompt,
6 buildElementContextBlock,
7 type ElementContextSelection,
8 elementContextDedupKey,
9 extractTrailingElementContexts,
10 formatElementContextLabel,
11 formatElementContextSourceLabel,
12 newElementContextId,
13 normalizeElementContextSelection,
14} from "./elementContext";
15
16function makePayload(overrides?: Partial<PickedElementPayload>): PickedElementPayload {
17 return {
18 pageUrl: "https://example.com/dashboard",
19 pageTitle: "Dashboard",
20 tagName: "BUTTON",
21 selector: "button.submit",
22 htmlPreview: '<button class="submit">Save</button>',
23 componentName: "SubmitButton",
24 source: {
25 functionName: "SubmitButton",
26 fileName: "/repo/src/Button.tsx",
27 lineNumber: 12,
28 columnNumber: 5,
29 },
30 stack: [
31 {
32 functionName: "SubmitButton",
33 fileName: "/repo/src/Button.tsx",
34 lineNumber: 12,
35 columnNumber: 5,
36 },
37 ],
38 styles: ".submit { color: white; }",
39 pickedAt: "2026-05-03T18:00:00.000Z",
40 ...overrides,
41 };
42}
43
44function makeSelection(overrides?: Partial<ElementContextSelection>): ElementContextSelection {
45 return {
46 pageUrl: "https://example.com/dashboard",
47 pageTitle: "Dashboard",
48 tagName: "button",
49 selector: "button.submit",
50 htmlPreview: '<button class="submit">Save</button>',
51 componentName: "SubmitButton",
52 source: {
53 functionName: "SubmitButton",
54 fileName: "/repo/src/Button.tsx",
55 lineNumber: 12,
56 columnNumber: 5,
57 },
58 styles: ".submit { color: white; }",
59 ...overrides,
60 };
61}
62
63describe("normalizeElementContextSelection", () => {
64 it("lowercases the tag, trims strings, and prefers `source` over `stack[0]`", () => {
65 const result = normalizeElementContextSelection(
66 makePayload({
67 tagName: " Button ",
68 pageUrl: " https://example.com ",
69 pageTitle: " Dashboard ",
70 selector: " ",
71 componentName: " ",
72 source: {
73 functionName: " Outer ",
74 fileName: " /repo/Outer.tsx ",
75 lineNumber: 7,
76 columnNumber: 0,
77 },
78 stack: [
79 {
80 functionName: "Inner",
81 fileName: "/repo/Inner.tsx",
82 lineNumber: 99,
83 columnNumber: 9,
84 },
85 ],
86 }),
87 );
88 expect(result).not.toBeNull();
89 expect(result?.tagName).toBe("button");
90 expect(result?.pageUrl).toBe("https://example.com");
91 expect(result?.pageTitle).toBe("Dashboard");
92 expect(result?.selector).toBeNull();
93 expect(result?.componentName).toBeNull();
94 expect(result?.source).toEqual({
95 functionName: "Outer",
96 fileName: "/repo/Outer.tsx",
97 lineNumber: 7,
98 columnNumber: 0,
99 });
100 });
101
102 it("returns null when pageUrl or tagName is empty", () => {
103 expect(normalizeElementContextSelection(makePayload({ pageUrl: "" }))).toBeNull();
104 expect(normalizeElementContextSelection(makePayload({ tagName: " " }))).toBeNull();
105 });
106
107 it("clamps oversized htmlPreview / styles so we don't blow localStorage", () => {
108 const huge = "x".repeat(10_000);
109 const result = normalizeElementContextSelection(
110 makePayload({ htmlPreview: huge, styles: huge }),
111 );
112 expect(result).not.toBeNull();
113 expect(result!.htmlPreview.length).toBeLessThanOrEqual(4000);
114 expect(result!.styles.length).toBeLessThanOrEqual(4000);
115 // Truncated values should end with the ellipsis sentinel
116 expect(result!.htmlPreview.endsWith("…")).toBe(true);
117 expect(result!.styles.endsWith("…")).toBe(true);
118 });
119
120 it("normalizes Windows line endings inside html/styles", () => {
121 const result = normalizeElementContextSelection(
122 makePayload({ htmlPreview: "<a>\r\nhi\r\n</a>", styles: ".a {\r\n color: red;\r\n}" }),
123 );
124 expect(result?.htmlPreview).toBe("<a>\nhi\n</a>");
125 expect(result?.styles).toBe(".a {\n color: red;\n}");
126 });
127
128 it("falls back to stack[0] when payload.source is null", () => {
129 const result = normalizeElementContextSelection(
130 makePayload({
131 source: null,
132 stack: [
133 {
134 functionName: "FromStack",
135 fileName: "/repo/FromStack.tsx",
136 lineNumber: 3,
137 columnNumber: null,
138 },
139 ],
140 }),
141 );
142 expect(result?.source).toEqual({
143 functionName: "FromStack",
144 fileName: "/repo/FromStack.tsx",
145 lineNumber: 3,
146 columnNumber: null,
147 });
148 });
149});
150
151describe("formatElementContextLabel", () => {
152 it("prefers component name over tag name", () => {
153 expect(formatElementContextLabel(makeSelection())).toBe("<SubmitButton>");
154 });
155
156 it("falls back to tag name when no component name is present", () => {
157 expect(formatElementContextLabel(makeSelection({ componentName: null }))).toBe("<button>");
158 });
159
160 it("truncates very long tag names", () => {
161 const tagName = "custom-".concat("x".repeat(60));
162 const result = formatElementContextLabel(makeSelection({ componentName: null, tagName }));
163 expect(result.length).toBeLessThan(tagName.length);
164 expect(result.endsWith("…>")).toBe(true);
165 });
166});
167
168describe("formatElementContextSourceLabel", () => {
169 it("renders basename + line number", () => {
170 expect(formatElementContextSourceLabel(makeSelection())).toBe("Button.tsx:12");
171 });
172
173 it("returns null when source has no fileName", () => {
174 expect(formatElementContextSourceLabel(makeSelection({ source: null }))).toBeNull();
175 });
176
177 it("omits line number when missing", () => {
178 expect(
179 formatElementContextSourceLabel(
180 makeSelection({
181 source: {
182 functionName: null,
183 fileName: "/a/b/Foo.tsx",
184 lineNumber: null,
185 columnNumber: null,
186 },
187 }),
188 ),
189 ).toBe("Foo.tsx");
190 });
191});
192
193describe("elementContextDedupKey", () => {
194 it("treats picks of the same element on the same page as duplicates", () => {
195 const first = makeSelection();
196 const second = makeSelection({ htmlPreview: "different preview", styles: "different styles" });
197 expect(elementContextDedupKey(first)).toBe(elementContextDedupKey(second));
198 });
199
200 it("differentiates picks with different selectors", () => {
201 expect(elementContextDedupKey(makeSelection())).not.toBe(
202 elementContextDedupKey(makeSelection({ selector: "button.cancel" })),
203 );
204 });
205
206 it("differentiates picks with different page urls", () => {
207 expect(elementContextDedupKey(makeSelection())).not.toBe(
208 elementContextDedupKey(makeSelection({ pageUrl: "https://example.com/other" })),
209 );
210 });
211});
212
213describe("buildElementContextBlock + appendElementContextsToPrompt", () => {
214 it("returns empty string for empty contexts", () => {
215 expect(buildElementContextBlock([])).toBe("");
216 expect(appendElementContextsToPrompt("Hello", [])).toBe("Hello");
217 });
218
219 it("serializes a context with header / url / selector / source / html / styles", () => {
220 const block = buildElementContextBlock([makeSelection()]);
221 expect(block.startsWith("<element_context>")).toBe(true);
222 expect(block.endsWith("</element_context>")).toBe(true);
223 expect(block).toContain("- <SubmitButton> (Button.tsx:12):");
224 expect(block).toContain(" url: https://example.com/dashboard");
225 expect(block).toContain(" selector: button.submit");
226 expect(block).toContain(" source: /repo/src/Button.tsx:12:5");
227 expect(block).toContain(" html:");
228 expect(block).toContain(" styles:");
229 });
230
231 it("appends with a blank line separator when prompt has text", () => {
232 expect(appendElementContextsToPrompt("Investigate this", [makeSelection()])).toBe(
233 [
234 "Investigate this",
235 "",
236 "<element_context>",
237 "- <SubmitButton> (Button.tsx:12):",
238 " url: https://example.com/dashboard",
239 " selector: button.submit",
240 " source: /repo/src/Button.tsx:12:5",
241 " html:",
242 ' <button class="submit">Save</button>',
243 " styles:",
244 " .submit { color: white; }",
245 "</element_context>",
246 ].join("\n"),
247 );
248 });
249
250 it("emits no leading blank when prompt is empty", () => {
251 expect(
252 appendElementContextsToPrompt("", [makeSelection()]).startsWith("<element_context>"),
253 ).toBe(true);
254 });
255});
256
257describe("extractTrailingElementContexts", () => {
258 it("round-trips appendElementContextsToPrompt and recovers prompt + entries", () => {
259 const prompt = appendElementContextsToPrompt("Investigate this", [
260 makeSelection(),
261 makeSelection({ selector: "button.cancel", componentName: "CancelButton" }),
262 ]);
263 const result = extractTrailingElementContexts(prompt);
264 expect(result.promptText).toBe("Investigate this");
265 expect(result.contextCount).toBe(2);
266 expect(result.contexts.map((c) => c.header)).toEqual([
267 "<SubmitButton> (Button.tsx:12)",
268 "<CancelButton> (Button.tsx:12)",
269 ]);
270 expect(result.contexts[0]?.body).toContain("url: https://example.com/dashboard");
271 expect(result.contexts[0]?.body).toContain("selector: button.submit");
272 });
273
274 it("returns the original prompt unchanged when no trailing block exists", () => {
275 expect(extractTrailingElementContexts("hi")).toEqual({
276 promptText: "hi",
277 contextCount: 0,
278 contexts: [],
279 });
280 });
281});
282
283describe("newElementContextId", () => {
284 it("returns a non-empty string with the element prefix", () => {
285 const id = newElementContextId();
286 expect(id.startsWith("el_")).toBe(true);
287 expect(id.length).toBeGreaterThan(3);
288 });
289
290 it("returns unique ids on repeated calls", () => {
291 const ids = new Set(Array.from({ length: 10 }, () => newElementContextId()));
292 expect(ids.size).toBe(10);
293 });
294});