-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathTaxonomySidebar.test.tsx
More file actions
419 lines (346 loc) · 13.6 KB
/
Copy pathTaxonomySidebar.test.tsx
File metadata and controls
419 lines (346 loc) · 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
import { Toasty } from "@cloudflare/kumo";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import * as React from "react";
import { describe, it, expect, vi, beforeEach } from "vitest";
import { userEvent } from "vitest/browser";
import { TaxonomySidebar } from "../../src/components/TaxonomySidebar";
import { render } from "../utils/render.tsx";
vi.mock("../../src/lib/api/client.js", async () => {
const actual = await vi.importActual("../../src/lib/api/client.js");
return {
...actual,
apiFetch: vi.fn(),
};
});
import { apiFetch } from "../../src/lib/api/client.js";
interface TestTaxonomy {
id: string;
name: string;
label: string;
labelSingular?: string;
hierarchical: boolean;
collections: string[];
}
interface TestTerm {
id: string;
name: string;
slug: string;
label: string;
parentId?: string | null;
children: TestTerm[];
}
const tagsTaxonomy: TestTaxonomy = {
id: "tax_tags",
name: "tags",
label: "Tags",
labelSingular: "Tag",
hierarchical: false,
collections: ["products"],
};
const categoriesTaxonomy: TestTaxonomy = {
id: "tax_categories",
name: "categories",
label: "Categories",
labelSingular: "Category",
hierarchical: true,
collections: ["products"],
};
const alphaTerm = makeTerm("term_alpha", "Alpha");
const betaTerm = makeTerm("term_beta", "Beta");
function makeTerm(id: string, label: string): TestTerm {
return {
id,
name: label.toLowerCase(),
slug: label.toLowerCase(),
label,
parentId: null,
children: [],
};
}
function dataResponse(data: unknown) {
return Promise.resolve(
new Response(JSON.stringify({ data }), {
status: 200,
headers: { "Content-Type": "application/json" },
}),
);
}
function mockApiFetch({
taxonomies = [tagsTaxonomy],
terms = [alphaTerm, betaTerm],
entryTerms = [],
createdTerm = makeTerm("term_created", "Gamma"),
}: {
taxonomies?: TestTaxonomy[];
terms?: TestTerm[];
entryTerms?: TestTerm[];
createdTerm?: TestTerm;
} = {}) {
vi.mocked(apiFetch).mockImplementation((url: string | URL | Request, init?: RequestInit) => {
const urlString = typeof url === "string" ? url : url instanceof URL ? url.toString() : url.url;
const path = new URL(urlString, "http://localhost").pathname;
const method = init?.method ?? "GET";
if (method === "GET" && path === "/_emdash/api/taxonomies") {
return dataResponse({ taxonomies });
}
if (method === "GET" && path === "/_emdash/api/taxonomies/tags/terms") {
return dataResponse({ terms });
}
if (method === "GET" && path === "/_emdash/api/taxonomies/categories/terms") {
return dataResponse({ terms });
}
if (method === "GET" && path === "/_emdash/api/content/products/entry_1/terms/tags") {
return dataResponse({ terms: entryTerms });
}
if (method === "POST" && path === "/_emdash/api/taxonomies/tags/terms") {
return dataResponse({ term: createdTerm });
}
return dataResponse({});
});
}
function Wrapper({ children }: { children: React.ReactNode }) {
const queryClient = React.useMemo(
() =>
new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
}),
[],
);
return (
<QueryClientProvider client={queryClient}>
<Toasty>{children}</Toasty>
</QueryClientProvider>
);
}
describe("TaxonomySidebar", () => {
beforeEach(() => {
vi.clearAllMocks();
mockApiFetch();
});
it("shows existing flat taxonomy terms when the tag picker receives focus", async () => {
const screen = await render(<TaxonomySidebar collection="products" />, { wrapper: Wrapper });
await expect.element(screen.getByLabelText("Add Tags")).toBeInTheDocument();
expect(screen.getByRole("option", { name: /^Alpha$/ }).query()).toBeNull();
await screen.getByLabelText("Add Tags").click();
await expect.element(screen.getByRole("option", { name: /^Alpha$/ })).toBeInTheDocument();
await expect.element(screen.getByRole("option", { name: /^Beta$/ })).toBeInTheDocument();
});
it("opens existing terms when the tag picker receives keyboard focus", async () => {
const screen = await render(<TaxonomySidebar collection="products" />, { wrapper: Wrapper });
const input = screen.getByLabelText("Add Tags");
await userEvent.tab();
expect(document.activeElement).toBe(input.element());
await expect.element(screen.getByRole("listbox")).toBeInTheDocument();
await expect.element(screen.getByRole("option", { name: "Alpha" })).toBeInTheDocument();
});
it("filters flat taxonomy terms while preserving the create option for new input", async () => {
const screen = await render(<TaxonomySidebar collection="products" />, { wrapper: Wrapper });
const input = screen.getByLabelText("Add Tags");
await input.fill("Alp");
await expect.element(screen.getByRole("option", { name: /^Alpha$/ })).toBeInTheDocument();
expect(screen.getByRole("option", { name: /^Beta$/ }).query()).toBeNull();
await expect.element(screen.getByText('Create "Alp"')).toBeInTheDocument();
});
it("shows every match and ranks exact, prefix, then substring labels deterministically", async () => {
mockApiFetch({
terms: [
makeTerm("term_web", "Web Security"),
makeTerm("term_operations", "Security Operations"),
makeTerm("term_cameras", "Security Cameras"),
makeTerm("term_news", "Security News"),
makeTerm("term_engineering", "Security Engineering"),
makeTerm("term_compliance", "Security Compliance"),
makeTerm("term_security", "Security"),
],
});
const screen = await render(<TaxonomySidebar collection="products" />, { wrapper: Wrapper });
await screen.getByLabelText("Add Tags").fill("security");
const options = screen.getByRole("option").elements();
expect(options.map((option) => option.textContent?.trim())).toEqual([
"Security",
"Security Cameras",
"Security Compliance",
"Security Engineering",
"Security News",
"Security Operations",
"Web Security",
]);
expect(screen.getByText('Create "security"').query()).toBeNull();
});
it("uses accessible combobox and listbox semantics", async () => {
const screen = await render(<TaxonomySidebar collection="products" />, { wrapper: Wrapper });
const input = screen.getByRole("combobox", { name: "Add Tags" });
await input.click();
await expect.element(screen.getByRole("listbox")).toBeInTheDocument();
await expect.element(screen.getByRole("option", { name: "Alpha" })).toBeInTheDocument();
expect(input.element().getAttribute("aria-controls")).toBe(
screen.getByRole("listbox").element().id,
);
});
it("selects a result beyond the first five with a pointer", async () => {
const onChange = vi.fn();
mockApiFetch({
terms: [
...Array.from({ length: 11 }, (_, index) =>
makeTerm(`term_${index + 1}`, `Security ${String(index + 1).padStart(2, "0")}`),
),
makeTerm("term_12", "Web Security"),
],
});
const screen = await render(<TaxonomySidebar collection="products" onChange={onChange} />, {
wrapper: Wrapper,
});
await screen.getByLabelText("Add Tags").fill("security");
const listbox = screen.getByRole("listbox");
const listboxElement = listbox.element();
expect(listboxElement.scrollHeight).toBeGreaterThan(listboxElement.clientHeight);
expect(listboxElement.scrollTop).toBe(0);
await listbox.wheel({ delta: { y: 400 } });
await vi.waitFor(() => expect(listboxElement.scrollTop).toBeGreaterThan(0));
await screen.getByRole("option", { name: "Web Security" }).click();
expect(onChange).toHaveBeenCalledWith("tags", ["term_12"]);
await expect.element(screen.getByLabelText("Remove Web Security")).toBeInTheDocument();
});
it("navigates to and selects a later result with the keyboard", async () => {
const onChange = vi.fn();
mockApiFetch({
terms: [
makeTerm("term_security", "Security"),
...Array.from({ length: 10 }, (_, index) =>
makeTerm(`term_${index + 1}`, `Security ${String(index + 1).padStart(2, "0")}`),
),
makeTerm("term_web", "Web Security"),
],
});
const screen = await render(<TaxonomySidebar collection="products" onChange={onChange} />, {
wrapper: Wrapper,
});
await screen.getByLabelText("Add Tags").fill("security");
const listbox = screen.getByRole("listbox").element();
for (let index = 0; index < 11; index += 1) {
await userEvent.keyboard("{ArrowDown}");
}
expect(listbox.scrollTop).toBeGreaterThan(0);
await userEvent.keyboard("{Enter}");
expect(onChange).toHaveBeenCalledWith("tags", ["term_web"]);
await expect.element(screen.getByLabelText("Remove Web Security")).toBeInTheDocument();
});
it("wraps ArrowUp from the first result to the last result", async () => {
const onChange = vi.fn();
mockApiFetch({
terms: [
makeTerm("term_security", "Security"),
makeTerm("term_news", "Security News"),
makeTerm("term_web", "Web Security"),
],
});
const screen = await render(<TaxonomySidebar collection="products" onChange={onChange} />, {
wrapper: Wrapper,
});
await screen.getByLabelText("Add Tags").fill("security");
await userEvent.keyboard("{ArrowUp}");
await userEvent.keyboard("{Enter}");
expect(onChange).toHaveBeenCalledWith("tags", ["term_web"]);
});
it("closes the suggestion list with Escape and keeps focus in the input", async () => {
const screen = await render(<TaxonomySidebar collection="products" />, { wrapper: Wrapper });
const input = screen.getByLabelText("Add Tags");
await input.fill("a");
await expect.element(screen.getByRole("listbox")).toBeInTheDocument();
await userEvent.keyboard("{Escape}");
expect(screen.getByRole("listbox").query()).toBeNull();
expect(document.activeElement).toBe(input.element());
});
it("shows a folded exact match first and prevents duplicate creation", async () => {
mockApiFetch({
terms: [
makeTerm("term_mexico_city", "Mexico City"),
makeTerm("term_mexico_news", "Mexico News"),
makeTerm("term_mexico_food", "Mexico Food"),
makeTerm("term_mexico_travel", "Mexico Travel"),
makeTerm("term_mexico_history", "Mexico History"),
makeTerm("term_mexico", "México"),
],
});
const screen = await render(<TaxonomySidebar collection="products" />, { wrapper: Wrapper });
await screen.getByLabelText("Add Tags").fill("Mexico");
expect(screen.getByRole("option").elements()[0]?.textContent?.trim()).toBe("México");
expect(screen.getByText('Create "Mexico"').query()).toBeNull();
});
it("does not suggest terms already assigned to the entry", async () => {
mockApiFetch({ entryTerms: [alphaTerm] });
const screen = await render(<TaxonomySidebar collection="products" entryId="entry_1" />, {
wrapper: Wrapper,
});
await expect.element(screen.getByLabelText("Remove Alpha")).toBeInTheDocument();
await screen.getByLabelText("Add Tags").click();
expect(screen.getByRole("option", { name: /^Alpha$/ }).query()).toBeNull();
await expect.element(screen.getByRole("option", { name: /^Beta$/ })).toBeInTheDocument();
});
it("keeps the create prompt available when no flat taxonomy terms exist", async () => {
const onChange = vi.fn();
mockApiFetch({ terms: [] });
const screen = await render(<TaxonomySidebar collection="products" onChange={onChange} />, {
wrapper: Wrapper,
});
const input = screen.getByLabelText("Add Tags");
await input.click();
expect(screen.getByText('Create "Gamma"').query()).toBeNull();
await input.fill("Gamma");
await expect.element(screen.getByText('Create "Gamma"')).toBeInTheDocument();
await screen.getByText('Create "Gamma"').click();
await vi.waitFor(() => {
expect(apiFetch).toHaveBeenCalledWith(
"/_emdash/api/taxonomies/tags/terms",
expect.objectContaining({
method: "POST",
body: JSON.stringify({ label: "Gamma" }),
}),
);
});
expect(onChange).toHaveBeenCalledWith("tags", ["term_created"]);
});
it("lets the server derive the slug for an inline Unicode term", async () => {
mockApiFetch({ terms: [] });
const screen = await render(<TaxonomySidebar collection="products" />, { wrapper: Wrapper });
await screen.getByLabelText("Add Tags").fill("音楽");
await screen.getByText('Create "音楽"').click();
await vi.waitFor(() => {
const call = vi.mocked(apiFetch).mock.calls.find(([, init]) => init?.method === "POST");
expect(call).toBeDefined();
const body = typeof call?.[1]?.body === "string" ? JSON.parse(call[1].body) : undefined;
expect(body).toEqual({ label: "音楽" });
});
});
it("continues to render hierarchical taxonomies as a checkbox tree", async () => {
mockApiFetch({ taxonomies: [categoriesTaxonomy], terms: [alphaTerm] });
const screen = await render(<TaxonomySidebar collection="products" />, { wrapper: Wrapper });
await expect.element(screen.getByText("Categories")).toBeInTheDocument();
await expect.element(screen.getByText("Alpha")).toBeInTheDocument();
expect(screen.getByLabelText("Add Categories").query()).toBeNull();
});
it("selects Arabic matches when the interface direction is RTL", async () => {
const previousDirection = document.documentElement.dir;
document.documentElement.dir = "rtl";
const onChange = vi.fn();
mockApiFetch({
terms: [
makeTerm("term_network", "أمن الشبكات"),
makeTerm("term_information", "أمن المعلومات"),
makeTerm("term_cloud", "الأمن السحابي"),
],
});
try {
const screen = await render(<TaxonomySidebar collection="products" onChange={onChange} />, {
wrapper: Wrapper,
});
await screen.getByLabelText("Add Tags").fill("أمن");
const listbox = screen.getByRole("listbox");
await expect.element(listbox).toBeInTheDocument();
await screen.getByRole("option", { name: "أمن المعلومات" }).click();
expect(onChange).toHaveBeenCalledWith("tags", ["term_information"]);
} finally {
document.documentElement.dir = previousDirection;
}
});
});