-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathadmin.ts
More file actions
640 lines (558 loc) · 18.5 KB
/
Copy pathadmin.ts
File metadata and controls
640 lines (558 loc) · 18.5 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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
/**
* Admin Page Object for E2E tests
*
* Provides a clean API for interacting with the EmDash admin UI.
*/
import { type Page, expect } from "@playwright/test";
// Regex patterns
const ADMIN_URL_PATTERN = /\/_emdash\/admin/;
const ADMIN_DASHBOARD_PATTERN = /\/_emdash\/admin\/?$/;
const CONTENT_ID_EXTRACTION_PATTERN = /\/content\/[^/]+\/([^/]+)$/;
const MENU_URL_PATTERN = /\/_emdash\/admin\/menus\//;
const SETUP_PAGE_PATTERN = /\/_emdash\/admin\/setup/;
const DEFAULT_LOCALE_SUFFIX_PATTERN = / \(default\)$/;
export class AdminPage {
readonly page: Page;
readonly baseUrl = "/_emdash/admin";
constructor(page: Page) {
this.page = page;
}
/**
* Authenticate using dev bypass (creates session)
* Call this before accessing protected pages.
*
* Navigates through the bypass URLs which sets cookies in the browser context.
*/
async devBypassAuth(): Promise<void> {
// Set up the site and establish a session, landing on the shell-free
// auth/me JSON endpoint instead of the admin shell. The shell opens
// the first-login welcome modal whenever its currentUser query
// resolves with isFirstLogin — on a cold workerd start that can be
// seconds after the sidebar renders, after dismissOnboardingModal()'s
// 2s visibility window has passed, leaving the modal covering the
// page (actions run 28678460523, E2E Cloudflare shard 3/8). Clearing
// the flag before the shell ever loads removes the race instead of
// retiming it.
// The bypass redirects via meta refresh, and its ?redirect= query
// contains the auth/me path — so match on pathname, not the full URL,
// or the wait resolves on the bypass page itself and the next goto
// races the pending redirect.
await this.page.goto("/_emdash/api/setup/dev-bypass?redirect=/_emdash/api/auth/me");
await this.page.waitForURL((url) => url.pathname === "/_emdash/api/auth/me", {
timeout: 30000,
});
// page.request shares the session cookie; X-EmDash-Request is the
// CSRF header the auth middleware requires on state-changing routes.
const dismissed = await this.page.request.post("/_emdash/api/auth/me", {
headers: { "X-EmDash-Request": "1" },
data: { action: "dismissWelcome" },
});
expect(dismissed.status()).toBe(200);
// Load the admin shell with the first-login flag already cleared.
await this.page.goto(`${this.baseUrl}/`);
await this.page.waitForURL(ADMIN_URL_PATTERN, { timeout: 30000 });
// Wait for page to be usable. Race networkidle (Vite dep re-optimization) against
// the hydration signal so HMR websocket can't stall us indefinitely.
await Promise.race([
this.page.waitForLoadState("networkidle").catch(() => {}),
this.waitForHydration().catch(() => {}),
]);
// Remove any vite error overlay that appeared during SSR
await this.dismissViteOverlay();
// If we got a server error, reload — the error is usually transient
const hasErrorOverlay = await this.page.locator("vite-error-overlay").count();
if (hasErrorOverlay > 0) {
await this.dismissViteOverlay();
await this.page.reload();
}
// Wait for the shell to fully hydrate
await this.waitForShell();
}
/**
* Navigate to an admin page
*/
async goto(path = "/"): Promise<void> {
const url = path === "/" ? this.baseUrl : `${this.baseUrl}${path}`;
await this.page.goto(url);
}
/**
* Wait for React hydration to complete.
* Astro removes the `ssr` attribute from `<astro-island>` after hydration.
*/
async waitForHydration(): Promise<void> {
await this.page.waitForSelector("astro-island:not([ssr])", { timeout: 15000 });
}
/**
* Wait for the admin shell to be ready (hydrated and interactive)
*/
async waitForShell(): Promise<void> {
// Dismiss vite error overlay if present (from previous request errors)
await this.dismissViteOverlay();
// Wait for sidebar to appear (indicates manifest loaded and React hydrated)
const maxRetries = 3;
let lastError: unknown;
for (let i = 0; i < maxRetries; i++) {
try {
// Wait for both sidebar and hydration signal
await this.page.waitForSelector('aside[aria-label="Admin navigation"]', {
timeout: 15000,
});
await this.waitForHydration();
lastError = undefined;
break;
} catch (error) {
lastError = error;
if (i < maxRetries - 1) {
// Server may be restarting (Vite re-optimization). Retry with reload.
// Wrap in try/catch since reload itself can fail if server is mid-restart.
try {
await this.dismissViteOverlay();
await this.page.reload({ waitUntil: "load" });
await this.dismissViteOverlay();
} catch {
// Server still down — wait for it to come back before next retry
await this.page.waitForLoadState("load").catch(() => {});
}
}
}
}
if (lastError) {
throw lastError;
}
// Dismiss the onboarding "Welcome" modal if it appears
await this.dismissOnboardingModal();
}
/**
* Dismiss the onboarding "Welcome" modal if it appears
*/
async dismissOnboardingModal(): Promise<void> {
const getStartedBtn = this.page.locator('button:has-text("Get Started")');
if (await getStartedBtn.isVisible({ timeout: 2000 }).catch(() => false)) {
await getStartedBtn.click();
await this.page
.locator("[data-base-ui-inert]")
.waitFor({ state: "hidden", timeout: 5000 })
.catch(() => {});
}
}
/**
* Dismiss vite-error-overlay if present
*/
async dismissViteOverlay(): Promise<void> {
// Remove vite-error-overlay from DOM if present — it has aria-hidden="true"
// so Playwright's isVisible() won't detect it, but it still blocks pointer events
await this.page
.evaluate(() => {
document.querySelectorAll("vite-error-overlay").forEach((el) => el.remove());
})
.catch(() => {});
}
/**
* Wait for loading states to complete
*/
async waitForLoading(): Promise<void> {
// Wait for loading text and spinners to disappear
await this.page
.locator("text=Loading")
.waitFor({ state: "hidden", timeout: 15000 })
.catch(() => {});
await this.page
.locator(".animate-spin")
.waitFor({ state: "hidden", timeout: 10000 })
.catch(() => {});
}
// ============================================
// Navigation
// ============================================
/**
* Navigate to dashboard
*/
async goToDashboard(): Promise<void> {
await this.goto("/");
await this.waitForShell();
}
/**
* Navigate to content list for a collection
*/
async goToContent(collection: string): Promise<void> {
await this.goto(`/content/${collection}`);
await this.waitForShell();
}
/**
* Navigate to create new content
*/
async goToNewContent(collection: string): Promise<void> {
await this.goto(`/content/${collection}/new`);
await this.waitForShell();
}
/**
* Navigate to edit content
*/
async goToEditContent(collection: string, id: string): Promise<void> {
await this.goto(`/content/${collection}/${id}`);
await this.waitForShell();
}
/**
* Navigate to media library
*/
async goToMedia(): Promise<void> {
await this.goto("/media");
await this.waitForShell();
}
/**
* Navigate to menus list
*/
async goToMenus(): Promise<void> {
await this.goto("/menus");
await this.waitForShell();
}
/**
* Navigate to edit a specific menu
*/
async goToMenuEditor(name: string): Promise<void> {
await this.goto(`/menus/${name}`);
await this.waitForShell();
}
/**
* Navigate to settings
*/
async goToSettings(): Promise<void> {
await this.goto("/settings");
await this.waitForShell();
}
/**
* Navigate to setup wizard
*/
async goToSetup(): Promise<void> {
await this.goto("/setup");
await this.waitForHydration();
}
// ============================================
// Setup Wizard Actions
// ============================================
/**
* Complete the setup wizard
*/
async completeSetup(options: {
title: string;
tagline?: string;
includeContent?: boolean;
}): Promise<void> {
// Fill title
await this.page.fill("#title", options.title);
// Fill tagline if provided
if (options.tagline) {
await this.page.fill("#tagline", options.tagline);
}
// Handle content checkbox if it exists
if (options.includeContent !== undefined) {
const checkbox = this.page.locator("#includeContent");
if (await checkbox.isVisible()) {
const isChecked = await checkbox.isChecked();
if (options.includeContent && !isChecked) {
await checkbox.click();
} else if (!options.includeContent && isChecked) {
await checkbox.click();
}
}
}
// Submit
await this.page.click('button[type="submit"]');
}
// ============================================
// Content CRUD Actions
// ============================================
/**
* Create new content with field data
*/
async createContent(collection: string, data: Record<string, string>): Promise<string> {
await this.goToNewContent(collection);
// Fill in form fields
for (const [field, value] of Object.entries(data)) {
await this.fillField(field, value);
}
// Save
await this.clickSave();
await this.waitForSaveComplete();
// Return the new content ID from URL
const url = this.page.url();
const match = url.match(CONTENT_ID_EXTRACTION_PATTERN);
return match?.[1] || "";
}
/**
* Update content field
*/
async updateField(field: string, value: string): Promise<void> {
await this.fillField(field, value);
}
/**
* Fill a form field by slug (uses #field-{slug} convention)
*/
async fillField(slug: string, value: string): Promise<void> {
const input = this.page.locator(`#field-${slug}`);
await input.fill(value);
}
/**
* Click the save button. Editor pages now render two SaveButtons (one in
* the header, one at the bottom of the main column); both submit the same
* form so we click the first match.
*/
async clickSave(): Promise<void> {
await this.page.locator('button:has-text("Save")').first().click();
}
/**
* Wait for save to complete
*/
async waitForSaveComplete(): Promise<void> {
// Wait for the save button to show "Saved" or stop showing "Saving..."
await this.page
.getByRole("button", { name: "Saved" })
.first()
.waitFor({ timeout: 10000 })
.catch(() => {});
await this.waitForLoading();
}
/**
* Delete content item by clicking delete button
*/
async deleteContentItem(title: string): Promise<void> {
// Find the row with this title and click delete
const row = this.page.locator("tr", { hasText: title });
await row.locator('button[aria-label*="Delete"]').click();
// Handle confirmation
this.page.once("dialog", (dialog) => dialog.accept());
}
// ============================================
// Media Library Actions
// ============================================
/**
* Upload a file to media library
*/
async uploadMedia(filePath: string): Promise<void> {
// Click upload button to trigger file input
const fileInput = this.page.locator('input[type="file"]');
await fileInput.setInputFiles(filePath);
// Wait for upload to complete
await this.page.waitForResponse(
(response) => response.url().includes("/api/media") && response.status() === 200,
);
await this.waitForLoading();
}
/**
* Get count of media items
*/
async getMediaCount(): Promise<number> {
const items = this.page.locator('[class*="grid"] > div');
return items.count();
}
/**
* Delete a media item by filename
*/
async deleteMedia(filename: string): Promise<void> {
// Hover over the item to show delete button
const item = this.page.locator(`[alt="${filename}"]`).first();
await item.hover();
// Click delete
const deleteBtn = this.page.locator('button:has-text("Delete")').first();
await deleteBtn.click();
// Handle confirmation
this.page.once("dialog", (dialog) => dialog.accept());
}
// ============================================
// Menu Actions
// ============================================
/**
* Create a new menu
*/
async createMenu(name: string, label: string): Promise<void> {
// Click create menu button
await this.page.getByRole("button", { name: "Create Menu" }).first().click();
// Fill form
await this.page.getByLabel("Name").fill(name);
await this.page.getByLabel("Label").fill(label);
// Submit and wait for navigation
await Promise.all([
this.page.waitForURL(MENU_URL_PATTERN, {
timeout: 15000,
}),
this.page.getByRole("button", { name: "Create" }).click(),
]);
}
/**
* Add a custom link to current menu
*/
async addMenuLink(label: string, url: string): Promise<void> {
// Click add link button
await this.page.getByRole("button", { name: "Add Custom Link" }).first().click();
// Wait for dialog to appear
await this.page.waitForSelector('[role="dialog"]', { state: "visible", timeout: 5000 });
// Fill form (scope to dialog to avoid ambiguity)
const dialog = this.page.locator('[role="dialog"]');
await dialog.getByLabel("Label").fill(label);
await dialog.getByLabel("URL").fill(url);
// Submit
await dialog.getByRole("button", { name: "Add" }).click();
// Wait for dialog to close
await this.page.waitForSelector('[role="dialog"]', { state: "hidden" });
}
/**
* Delete a menu
*/
async deleteMenu(name: string): Promise<void> {
// Find menu row and click delete
const menuRow = this.page.locator(`a[href*="/menus/${name}"]`).first();
const row = menuRow.locator("..");
await row.locator('button:has(svg[class*="Trash"])').click();
// Confirm deletion
await this.page.click('button:has-text("Delete"):not([disabled])');
}
/**
* Get list of menu items
*/
async getMenuItems(): Promise<string[]> {
const items = this.page.locator(".border.rounded-lg.p-4 .font-medium");
const texts = await items.allTextContents();
return texts;
}
// ============================================
// i18n / Translation Actions
// ============================================
/**
* Get the locale column values from the content list table.
* Returns empty array if locale column is not shown.
*/
async getLocaleColumnValues(): Promise<string[]> {
const cells = this.page.locator("table tbody tr td span.rounded.bg-kumo-tint");
return cells.allTextContents();
}
/**
* Get the locale badge shown in the content editor header.
* Returns null if no locale badge is visible.
*/
async getEditorLocaleBadge(): Promise<string | null> {
const badge = this.page
.locator("span.rounded.bg-kumo-tint.text-xs.font-semibold.uppercase")
.first();
if (await badge.isVisible({ timeout: 3000 }).catch(() => false)) {
return badge.textContent();
}
return null;
}
/**
* Get available translation locales from the translations sidebar.
* Returns an array of locale codes shown in the sidebar.
*/
async getTranslationSidebarLocales(): Promise<string[]> {
const sidebar = this.page.locator("div:has(> h3:text-is('Translations'))");
const localeCodes = sidebar.locator("span.text-xs.font-semibold.uppercase");
return localeCodes.allTextContents();
}
/**
* Click the "Translate" button for a specific locale in the translations sidebar.
*/
async clickTranslate(locale: string): Promise<void> {
// Find the translation row for this locale (the div containing the locale code)
const sidebar = this.page.locator("div:has(> h3:text-is('Translations'))");
const localeRow = sidebar.locator(`div:has(> div > span.uppercase:text-is("${locale}"))`);
await localeRow.getByRole("button", { name: "Translate" }).click();
}
/**
* Click "Edit" link for an existing translation in the sidebar.
*/
async clickEditTranslation(locale: string): Promise<void> {
const sidebar = this.page.locator("div:has(> h3:text-is('Translations'))");
const localeRow = sidebar.locator(`div:has(> div > span.uppercase:text-is("${locale}"))`);
await localeRow.getByRole("button", { name: "Edit" }).click();
}
/**
* Check if a "Translate" button exists for a locale in the translations sidebar.
*/
async hasTranslateButton(locale: string): Promise<boolean> {
const sidebar = this.page.locator("div:has(> h3:text-is('Translations'))");
const localeRow = sidebar.locator(`div:has(> div > span.uppercase:text-is("${locale}"))`);
return localeRow
.getByRole("button", { name: "Translate" })
.isVisible({ timeout: 3000 })
.catch(() => false);
}
/**
* Check if an "Edit" link exists for a locale in the translations sidebar.
*/
async hasEditTranslationLink(locale: string): Promise<boolean> {
const sidebar = this.page.locator("div:has(> h3:text-is('Translations'))");
const localeRow = sidebar.locator(`div:has(> div > span.uppercase:text-is("${locale}"))`);
return localeRow
.getByRole("button", { name: "Edit" })
.isVisible({ timeout: 3000 })
.catch(() => false);
}
/**
* Get the locale selected in the content list.
*/
async getLocaleFilterValue(): Promise<string | null> {
const select = this.page.getByRole("combobox", { name: "Locale" });
if (await select.isVisible({ timeout: 3000 }).catch(() => false)) {
const label = (await select.innerText()).trim();
return label === "All locales"
? ""
: label.replace(DEFAULT_LOCALE_SUFFIX_PATTERN, "").toLowerCase();
}
return null;
}
/**
* Change the locale filter in the content list.
*/
async setLocaleFilter(locale: string): Promise<void> {
await this.page.getByRole("combobox", { name: "Locale" }).click();
const label = locale
? new RegExp(`^${locale.toUpperCase()}(?: \\(default\\))?$`)
: "All locales";
await this.page.getByRole("option", { name: label }).click();
await this.waitForLoading();
}
// ============================================
// Assertions
// ============================================
/**
* Assert we're on the dashboard
*/
async expectDashboard(): Promise<void> {
await expect(this.page).toHaveURL(ADMIN_DASHBOARD_PATTERN);
}
/**
* Assert we're on the setup page
*/
async expectSetupPage(): Promise<void> {
await expect(this.page).toHaveURL(SETUP_PAGE_PATTERN);
}
/**
* Assert a toast message appears
*/
async expectToast(text: string): Promise<void> {
await expect(this.page.locator('[role="status"]', { hasText: text })).toBeVisible();
}
/**
* Assert content exists in list
*/
async expectContentInList(title: string): Promise<void> {
await expect(this.page.locator("td", { hasText: title })).toBeVisible();
}
/**
* Assert content does not exist in list
*/
async expectContentNotInList(title: string): Promise<void> {
await expect(this.page.locator("td", { hasText: title })).not.toBeVisible();
}
/**
* Assert menu exists in list
*/
async expectMenuInList(label: string): Promise<void> {
await expect(this.page.locator("h3", { hasText: label })).toBeVisible();
}
/**
* Assert page title
*/
async expectPageTitle(title: string): Promise<void> {
await expect(this.page.locator("h1").first()).toContainText(title);
}
}