Repository navigation
Expand file tree
/
Copy pathreader.spec.ts
More file actions
1153 lines (1104 loc) · 39.2 KB
/
Copy pathreader.spec.ts
File metadata and controls
1153 lines (1104 loc) · 39.2 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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import AxeBuilder from "@axe-core/playwright";
import { expect, type Page, test } from "@playwright/test";
import { feedSource, post, xPost, xSource } from "../src/lib/api.fixture";
import { parseFilters } from "../src/lib/navigation";
import type { Post, Source } from "../src/lib/types";
import { apiPath, emptyResponses, fulfillEmpty } from "./apiMock";
const legacyStorageKey = "dank-reader:library:v1";
const readStorageKey = "dank-reader:read:v1";
const maliciousHtml = `
<p>Collected article body with a safe link.</p>
<script>window.readerAttack = true</script>
<img src="/missing-test-image.png" onerror="window.readerAttack = true">
<a href="javascript:window.readerAttack=true">Unsafe link</a>
<a href="https://example.com/supporting-story">Supporting story</a>
<iframe srcdoc="<script>parent.readerAttack=true</script>"></iframe>
<form><input name="location"><button>Injected action</button></form>
<p style="position:fixed" id="main">Untrusted style</p>
`;
const article: Post = post({
id: "shared-id",
domain: "example.com",
url: "https://example.com/housing",
author: "Ada Writer",
title: "Housing policy, explained",
excerpt: "A clear account of housing policy and the decisions ahead.",
html: maliciousHtml,
created_at: "2026-10-08T10:00:00Z",
source: "rss",
thumbnail: null,
media: [],
});
const socialPost: Post = {
...article,
domain: "x.com",
url: "https://x.com/reporter/status/shared-id",
author: "@reporter",
title: "Housing dispatch from the city",
html: "<p>A short eyewitness housing dispatch.</p>",
source: "x",
x: xPost({ handle: "reporter", name: "City Reporter", icon_url: null }),
};
const sources: Source[] = [
feedSource({
domain: "example.com",
name: "Example News",
tags: ["politics", "news"],
count: 15,
}),
xSource({ domain: "x.com", name: "X", tags: ["social"], count: 1 }),
];
interface MockReader {
posts: Post[];
failPosts: boolean;
requests: URL[];
pageSize: number | null;
}
async function mockReader(page: Page): Promise<MockReader> {
const state: MockReader = {
posts: [
article,
socialPost,
...Array.from({ length: 13 }, (_, index) => ({
...article,
id: `article-${index}`,
title: `Housing report ${index + 1}`,
html: "<p>A collected report ready to read.</p>".repeat(30),
})),
],
failPosts: false,
requests: [],
pageSize: null,
};
await page.route("**/api/reader/**", async (route) => {
const url = new URL(route.request().url());
state.requests.push(url);
switch (apiPath(route)) {
case "/api/reader/sources":
return route.fulfill({
json: {
...emptyResponses["/api/reader/sources"],
sources,
total_posts: state.posts.length,
},
});
case "/api/reader/post": {
const post = state.posts.find(
(item) =>
item.domain === url.searchParams.get("domain") &&
item.id === url.searchParams.get("id"),
);
return post
? route.fulfill({ json: post })
: route.fulfill({
status: 404,
json: {
error: "Story not found.",
code: "not_found",
fields: [],
},
});
}
case "/api/reader/posts":
break;
default:
return fulfillEmpty(route);
}
if (state.failPosts) {
await route.fulfill({
status: 503,
json: {
error: "Collection temporarily unavailable.",
code: "unavailable",
fields: [],
},
});
return;
}
const domains = url.searchParams.getAll("domain");
const tags = url.searchParams.getAll("tag");
const query = url.searchParams.get("q")?.toLowerCase() ?? "";
const kind = url.searchParams.get("kind");
const posts = state.posts.filter(
(post) =>
(kind === "all" ||
(kind === "stories"
? post.source !== "reddit" && post.source !== "x"
: post.source === kind)) &&
(!domains.length || domains.includes(post.domain)) &&
(!tags.length ||
sources.some(
(source) =>
source.domain === post.domain &&
source.tags.some((tag) => tags.includes(tag)),
)) &&
(!query ||
`${post.title} ${post.excerpt}`.toLowerCase().includes(query)),
);
const offset = Number(url.searchParams.get("cursor") ?? 0);
const end = state.pageSize ? offset + state.pageSize : posts.length;
await route.fulfill({
json: {
posts: posts.slice(offset, end),
next_cursor: end < posts.length ? String(end) : null,
limited: false,
},
});
});
return state;
}
function story(page: Page, title = article.title) {
return page.getByRole("link", { name: `Read ${title}`, exact: true });
}
async function expectNoHorizontalOverflow(page: Page) {
expect(
await page.evaluate(
() =>
document.documentElement.scrollWidth <=
document.documentElement.clientWidth,
),
).toBe(true);
}
for (const width of [1280, 390, 320]) {
test(`distinguishes uncollected articles in the feed and reader at ${width}px`, async ({
page,
}, testInfo) => {
await page.setViewportSize({ width, height: 844 });
const state = await mockReader(page);
const missing = {
...article,
id: "uncollected",
title: "Microsoft Defender for Linux",
url: "https://techcommunity.microsoft.com/original-article",
html: "\n\n\n\n\n\n",
collection_incomplete: true,
excerpt: "",
};
state.posts = [missing, article];
await page.goto("/");
const missingCard = page
.locator(".post-card")
.filter({ has: story(page, missing.title) });
const collectedCard = page
.locator(".post-card")
.filter({ has: story(page) });
const badge = missingCard.getByText("Not collected", { exact: true });
await expect(badge).toBeVisible();
await expect(badge).toHaveAttribute("title", /Full text wasn’t collected/);
await expect(
missingCard.getByText(/min read|Open to read this story/),
).toHaveCount(0);
await expect(collectedCard.getByText("Not collected")).toHaveCount(0);
await expectNoHorizontalOverflow(page);
await page.screenshot({
path: testInfo.outputPath(`collection-feed-${width}.png`),
});
await story(page, missing.title).click();
const notice = page.getByRole("complementary", {
name: "Collection status",
});
await expect(
notice.getByRole("heading", { name: "Full text not collected" }),
).toBeVisible();
const original = notice.getByRole("link", {
name: "Read original article",
});
await expect(original).toHaveAttribute("href", missing.url);
await expect(original).toHaveAttribute("target", "_blank");
await original.focus();
await expect(original).toBeFocused();
await expect(page.locator(".article-body")).toHaveCount(0);
await expect(
page
.getByRole("main", { name: "Article reader" })
.getByText(/min read|YOU’VE REACHED THE END/),
).toHaveCount(0);
await expectNoHorizontalOverflow(page);
expect((await new AxeBuilder({ page }).analyze()).violations).toEqual([]);
await page.screenshot({
path: testInfo.outputPath(`collection-article-${width}.png`),
});
await page.getByRole("button", { name: "Back to your reading" }).click();
await expect(story(page, missing.title)).toBeFocused();
await expect(missingCard.getByText("Read", { exact: true })).toHaveCount(0);
expect(
await page.evaluate((key) => localStorage.getItem(key), readStorageKey),
).toBeNull();
await story(page).click();
await expect(
page.getByRole("complementary", { name: "Collection status" }),
).toHaveCount(0);
await expect(page.getByText("YOU’VE REACHED THE END")).toBeVisible();
});
}
for (const width of [1280, 390, 320]) {
test(`shows available text with an incomplete scrape warning at ${width}px`, async ({
page,
}, testInfo) => {
await page.setViewportSize({ width, height: 844 });
const state = await mockReader(page);
const partial = {
...article,
id: "incomplete",
title: "Article saved from its feed",
html: "The feed text is still available to read.",
collection_incomplete: true,
};
state.posts = [partial, article];
await page.goto("/");
const card = page.locator(".post-card").filter({
has: story(page, partial.title),
});
await expect(
card.getByText("Incomplete scrape", { exact: true }),
).toBeVisible();
await expect(card.getByText("Not collected", { exact: true })).toHaveCount(
0,
);
await expect(card.getByText(/min read/)).toBeVisible();
await expectNoHorizontalOverflow(page);
await page.screenshot({
path: testInfo.outputPath(`incomplete-feed-${width}.png`),
});
await story(page, partial.title).click();
const notice = page.getByRole("complementary", {
name: "Collection status",
});
await expect(
notice.getByRole("heading", { name: "Incomplete scrape" }),
).toBeVisible();
await expect(notice).toContainText(
"text, formatting or media may be missing",
);
await expect(page.locator(".article-body")).toHaveText(partial.html);
await expect(
page.getByRole("link", { name: "Read original", exact: true }),
).toHaveAttribute("href", partial.url);
await expectNoHorizontalOverflow(page);
expect((await new AxeBuilder({ page }).analyze()).violations).toEqual([]);
await page.screenshot({
path: testInfo.outputPath(`incomplete-article-${width}.png`),
});
state.posts[0] = {
...partial,
html: "<p>The restored article has its paragraphs.</p><p>And its formatting.</p>",
collection_incomplete: false,
};
await page.reload();
await expect(notice).toHaveCount(0);
await expect(
page.getByText("Incomplete scrape", { exact: true }),
).toHaveCount(0);
await expect(page.locator(".article-body p")).toHaveCount(2);
await page.getByRole("button", { name: "Back to your reading" }).click();
await expect(
card.getByText("Incomplete scrape", { exact: true }),
).toHaveCount(0);
});
}
test("opens a full article page and restores filters, loaded pages, focus and scroll through Back and Forward", async ({
page,
}) => {
const state = await mockReader(page);
state.pageSize = 5;
const filters = new URLSearchParams({
q: "housing",
mode: "words",
sort: "oldest",
domain: "example.com",
tag: "politics",
author: "Ada",
after: "2026-10-01",
before: "2026-10-08",
});
await page.goto(`/?${filters}`);
await expect(story(page)).toBeVisible();
await expect(
page.getByRole("searchbox", { name: "Search example.com" }),
).toHaveValue("housing");
await expect(
page.getByRole("combobox", { name: "Order stories" }),
).toHaveValue("oldest");
const request = state.requests.find(
(url) => url.pathname === "/api/reader/posts",
);
expect(parseFilters(request?.searchParams ?? new URLSearchParams())).toEqual(
parseFilters(filters),
);
await page.locator(".load-more").scrollIntoViewIfNeeded();
await expect(page.locator(".post-card")).toHaveCount(10);
const target = story(page, "Housing report 5");
await target.scrollIntoViewIfNeeded();
const scroll = await page.evaluate(() => window.scrollY);
expect(scroll).toBeGreaterThan(100);
await target.click();
await expect(
page.getByRole("main", { name: "Article reader" }),
).toBeVisible();
await expect(page.getByRole("dialog")).toHaveCount(0);
await expect(
page.getByRole("heading", { name: "All", exact: true }),
).not.toBeVisible();
await expect(page.locator("body")).not.toHaveCSS("overflow", "hidden");
await expect.poll(() => page.evaluate(() => window.scrollY)).toBe(0);
await page
.getByRole("button", { name: "Back to stories", exact: true })
.click();
await expect(page.getByRole("main", { name: "Article reader" })).toHaveCount(
0,
);
expect(new URL(page.url()).searchParams.toString()).toBe(filters.toString());
await expect.poll(() => page.evaluate(() => window.scrollY)).toBe(scroll);
await expect(target).toBeFocused();
await expect(page.locator(".post-card:visible")).toHaveCount(10);
await target.click();
await expect(
page.getByRole("main", { name: "Article reader" }),
).toBeVisible();
await page.evaluate(() => window.scrollTo(0, 300));
await expect.poll(() => page.evaluate(() => window.scrollY)).toBe(300);
await page.goBack();
await expect(page.getByRole("main", { name: "Article reader" })).toHaveCount(
0,
);
expect(new URL(page.url()).searchParams.toString()).toBe(filters.toString());
await expect.poll(() => page.evaluate(() => window.scrollY)).toBe(scroll);
await expect(target).toBeFocused();
await expect(page.locator(".post-card:visible")).toHaveCount(10);
await page.goForward();
await expect(
page.getByRole("main", { name: "Article reader" }),
).toBeVisible();
await expect.poll(() => page.evaluate(() => window.scrollY)).toBe(300);
await page
.getByRole("button", { name: "Back to stories", exact: true })
.click();
await expect(target).toBeFocused();
await expect.poll(() => page.evaluate(() => window.scrollY)).toBe(scroll);
});
for (const width of [1280, 390]) {
test(`loads successive pages on scroll and stops at the end at ${width}px`, async ({
page,
}, testInfo) => {
await page.setViewportSize({ width, height: 844 });
const state = await mockReader(page);
state.pageSize = 5;
await page.goto("/");
const cards = page.locator(".post-card");
await expect(cards).toHaveCount(5);
const initialRequests = state.requests.length;
await page.locator(".load-more").scrollIntoViewIfNeeded();
await expect(cards).toHaveCount(10);
await expect(story(page)).toHaveCount(1);
await expect(story(page, socialPost.title)).toHaveCount(1);
const scroll = await page.evaluate(() => window.scrollY);
expect(scroll).toBeGreaterThan(0);
await page.screenshot({ path: testInfo.outputPath("scrolled-feed.png") });
await expectNoHorizontalOverflow(page);
await page.locator(".load-more").scrollIntoViewIfNeeded();
await expect(cards).toHaveCount(15);
await expect(page.locator(".load-more")).toHaveCount(0);
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
await page.waitForTimeout(250);
expect(
state.requests
.slice(initialRequests)
.filter((url) => url.pathname === "/api/reader/posts")
.map((url) => url.searchParams.get("cursor")),
).toEqual(["5", "10"]);
});
}
test("loads short pages until the viewport is filled or the feed ends", async ({
page,
}) => {
await page.setViewportSize({ width: 1280, height: 1200 });
const state = await mockReader(page);
state.pageSize = 1;
state.posts = state.posts.slice(0, 3);
await page.goto("/");
await expect(page.locator(".post-card")).toHaveCount(3);
await expect(page.locator(".load-more")).toHaveCount(0);
expect(await page.evaluate(() => window.scrollY)).toBe(0);
expect(
state.requests
.filter((url) => url.searchParams.has("cursor"))
.map((url) => url.searchParams.get("cursor")),
).toEqual(["1", "2"]);
});
test("keeps one next-page request in flight while the bottom remains visible", async ({
page,
}) => {
const state = await mockReader(page);
state.pageSize = 5;
await page.goto("/");
await expect(page.locator(".post-card")).toHaveCount(5);
let release = () => {};
const pending = new Promise<void>((resolve) => {
release = resolve;
});
let requests = 0;
await page.route("**/api/reader/posts?**", async (route) => {
if (new URL(route.request().url()).searchParams.has("cursor")) {
requests += 1;
await pending;
}
await route.fallback();
});
await page.locator(".load-more").scrollIntoViewIfNeeded();
await expect(
page.getByRole("button", { name: "Loading stories" }),
).toBeDisabled();
for (let index = 0; index < 3; index += 1) {
await page.evaluate(() => window.scrollTo(0, 0));
await page.locator(".load-more").scrollIntoViewIfNeeded();
}
expect(requests).toBe(1);
release();
await expect(page.locator(".post-card")).toHaveCount(10);
expect(requests).toBe(1);
});
test("preserves loaded stories on a next-page error and retries only on request", async ({
page,
}) => {
const state = await mockReader(page);
state.pageSize = 5;
await page.goto("/");
await expect(page.locator(".post-card")).toHaveCount(5);
state.failPosts = true;
await page.locator(".load-more").scrollIntoViewIfNeeded();
await expect(page.getByRole("alert")).toContainText(
"Collection temporarily unavailable.",
);
await expect(page.locator(".post-card")).toHaveCount(5);
const requests = state.requests.length;
await page.waitForTimeout(1500);
expect(state.requests).toHaveLength(requests);
state.failPosts = false;
await page.getByRole("button", { name: "Try again", exact: true }).click();
await expect(page.locator(".post-card")).toHaveCount(10);
await expect(page.getByRole("alert")).toHaveCount(0);
expect(
state.requests
.filter((url) => url.pathname === "/api/reader/posts")
.at(-1)
?.searchParams.get("cursor"),
).toBe("5");
});
test("does not load hidden feed pages while reading an article", async ({
page,
}) => {
const state = await mockReader(page);
state.pageSize = 1;
await page.goto("/?article=article-0&article_source=example.com");
await expect(
page.getByRole("main", { name: "Article reader" }),
).toBeVisible();
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
await page.waitForTimeout(250);
expect(state.requests.some((url) => url.searchParams.has("cursor"))).toBe(
false,
);
});
test("starts a fresh cursor sequence after filters change", async ({
page,
}) => {
const state = await mockReader(page);
state.pageSize = 5;
await page.goto("/");
await expect(page.locator(".post-card")).toHaveCount(5);
const initialRequests = state.requests.length;
await page.locator(".load-more").scrollIntoViewIfNeeded();
await expect(page.locator(".post-card")).toHaveCount(10);
await page
.getByRole("searchbox", { name: "Search everything" })
.fill("report");
await page.getByRole("button", { name: "Search", exact: true }).click();
await expect(page.locator(".post-card")).toHaveCount(5);
await expect(story(page)).toHaveCount(0);
await page.locator(".load-more").scrollIntoViewIfNeeded();
await expect(page.locator(".post-card")).toHaveCount(10);
expect(
state.requests
.slice(initialRequests)
.filter((url) => url.pathname === "/api/reader/posts")
.map((url) => [
url.searchParams.get("q"),
url.searchParams.get("cursor"),
]),
).toEqual([
[null, "5"],
["report", null],
["report", "5"],
]);
});
test("keeps manual pagination available without IntersectionObserver", async ({
page,
}) => {
const state = await mockReader(page);
state.pageSize = 5;
await page.addInitScript(() => {
Reflect.deleteProperty(window, "IntersectionObserver");
});
await page.goto("/");
await expect(page.locator(".post-card")).toHaveCount(5);
await page.getByRole("button", { name: "More stories", exact: true }).click();
await expect(page.locator(".post-card")).toHaveCount(10);
});
test("opens source-specific deep links and returns to their filtered timeline", async ({
page,
}) => {
const state = await mockReader(page);
await page.goto("/?q=housing&article=shared-id&article_source=x.com");
const reader = page.getByRole("main", { name: "X post reader" });
await expect(
reader.getByRole("heading", { name: "Post by City Reporter", exact: true }),
).toBeVisible();
await expect(
reader.getByText("A short eyewitness housing dispatch."),
).toBeVisible();
expect(
state.requests.some(
(url) =>
url.pathname === "/api/reader/post" &&
url.searchParams.get("domain") === "x.com",
),
).toBe(true);
await expect(page.getByRole("dialog")).toHaveCount(0);
await page.reload();
await expect(
reader.getByRole("heading", { name: "Post by City Reporter", exact: true }),
).toBeVisible();
await reader
.getByRole("button", { name: "Back to stories", exact: true })
.click();
await expect(story(page)).toBeVisible();
await expect(
page.getByRole("searchbox", { name: "Search everything" }),
).toHaveValue("housing");
expect(new URL(page.url()).search).toBe("?q=housing");
});
test("keeps a failed article on its page with a working way back", async ({
page,
}) => {
await mockReader(page);
await page.goto("/?article=missing&article_source=example.com");
await expect(page.getByRole("alert")).toContainText("Story not found.");
await expect(page.getByRole("dialog")).toHaveCount(0);
await page
.getByRole("button", { name: "Back to stories", exact: true })
.click();
await expect(story(page)).toBeVisible();
});
test("keeps navigation and article controls focused on reading", async ({
page,
}) => {
await mockReader(page);
await page.goto("/");
await expect(story(page)).toBeVisible();
const sidebar = page.locator(".sidebar");
await expect(sidebar.locator(".brand img")).toHaveCount(0);
await expect(
sidebar.getByRole("link", { name: "DANK reader home" }),
).toHaveText("DANK");
await expect(page.locator('link[rel="icon"]')).toHaveAttribute(
"href",
"/favicon.svg",
);
await expect(page.locator("main .page-heading h1")).toHaveCount(0);
await expect(page.locator(".topbar h1")).toHaveText("All");
await expect(
sidebar.getByRole("button", { name: "All", exact: true }),
).toBeVisible();
await expect(
sidebar.getByRole("button", { name: "Sources", exact: true }),
).toBeVisible();
await expect(
sidebar.getByRole("button", { name: "Settings", exact: true }),
).toBeVisible();
await expect(
sidebar.getByText("Your workspace", { exact: true }),
).toHaveCount(0);
await expect(page.getByText("A quieter corner of the internet")).toHaveCount(
0,
);
await expect(page.getByText("Your personal reader")).toHaveCount(0);
await expect(page.getByText("YOUR FEEDS", { exact: true })).toHaveCount(0);
await expect(
page.getByText("A library with your point of view."),
).toHaveCount(0);
await expect(
page.getByText("Feeds & bookmarks stay in this browser."),
).toHaveCount(0);
await expect(page.getByRole("button", { name: /^Saved/ })).toHaveCount(0);
await expect(
page.getByRole("button", { name: /Create a feed|Make your first feed/ }),
).toHaveCount(0);
await expect(
page.getByRole("button", { name: /^(Save|Unsave) / }),
).toHaveCount(0);
await page.getByRole("button", { name: /^Filters/ }).click();
await expect(page.getByRole("button", { name: /Save.*feed/i })).toHaveCount(
0,
);
await story(page).click();
await expect(
page.getByRole("main", { name: "Article reader" }),
).toBeVisible();
await expect(
page.getByRole("button", { name: /^(Save|Unsave) / }),
).toHaveCount(0);
});
const legacyLibrary = JSON.stringify(
{
version: 1,
feeds: [
{
id: "legacy-politics",
name: "Politics",
filters: parseFilters(
new URLSearchParams("domain=example.com&q=housing"),
),
},
],
bookmarks: [article],
read: [JSON.stringify([article.domain, article.id])],
futureData: { preserved: true },
},
null,
2,
);
for (const view of ["saved", "legacy-politics"]) {
test(`opens the old ${view} view as All and preserves filters and local data`, async ({
page,
}) => {
await mockReader(page);
await page.addInitScript(
({ key, value }) => {
if (localStorage.getItem(key) === null)
localStorage.setItem(key, value);
},
{ key: legacyStorageKey, value: legacyLibrary },
);
await page.goto(`/?view=${view}&q=housing&domain=x.com&sort=oldest`);
await expect(
page.getByRole("heading", { name: "All", exact: true }),
).toBeVisible();
await expect(story(page, socialPost.title)).toBeVisible();
await expect(story(page)).toHaveCount(0);
await expect(
page.getByRole("searchbox", { name: "Search x.com" }),
).toHaveValue("housing");
await expect(
page.getByRole("combobox", { name: "Order stories" }),
).toHaveValue("oldest");
await expect(
page.getByRole("button", { name: "Politics", exact: true }),
).toHaveCount(0);
await story(page, socialPost.title).click();
await expect(
page.getByRole("main", { name: "X post reader" }),
).toBeVisible();
await page.reload();
await expect(
page.getByRole("main", { name: "X post reader" }),
).toBeVisible();
await page
.getByRole("button", { name: "Back to stories", exact: true })
.click();
await expect(
page.getByRole("heading", { name: "All", exact: true }),
).toBeVisible();
const params = new URL(page.url()).searchParams;
expect(params.get("q")).toBe("housing");
expect(params.getAll("domain")).toEqual(["x.com"]);
expect(params.get("sort")).toBe("oldest");
expect(
await page.evaluate((key) => localStorage.getItem(key), legacyStorageKey),
).toBe(legacyLibrary);
});
}
test("preserves old library data while recording read stories by source", async ({
page,
}) => {
await mockReader(page);
await page.addInitScript(
({ key, value }) => {
if (localStorage.getItem(key) === null) localStorage.setItem(key, value);
},
{ key: legacyStorageKey, value: legacyLibrary },
);
await page.goto("/");
const articleCard = page.locator(".post-card").filter({ has: story(page) });
const socialCard = page
.locator(".post-card")
.filter({ has: story(page, socialPost.title) });
await expect(articleCard.getByText("Read", { exact: true })).toBeVisible();
await expect(socialCard.getByText("Read", { exact: true })).toHaveCount(0);
await story(page, socialPost.title).click();
await expect(page.getByRole("main", { name: "X post reader" })).toBeVisible();
await page
.getByRole("button", { name: "Back to stories", exact: true })
.click();
await page.reload();
await expect(articleCard.getByText("Read", { exact: true })).toBeVisible();
await expect(socialCard.getByText("Read", { exact: true })).toBeVisible();
expect(
await page.evaluate((key) => localStorage.getItem(key), legacyStorageKey),
).toBe(legacyLibrary);
expect(
await page.evaluate((key) => localStorage.getItem(key), readStorageKey),
).not.toBeNull();
});
test("keeps corrupted legacy storage untouched while reading remains usable", async ({
page,
}) => {
await mockReader(page);
await page.addInitScript((key) => {
if (localStorage.getItem(key) === null)
localStorage.setItem(key, "{broken JSON");
}, legacyStorageKey);
await page.goto("/");
await expect(story(page)).toBeVisible();
await story(page).click();
await expect(
page.getByRole("main", { name: "Article reader" }),
).toBeVisible();
await page
.getByRole("button", { name: "Back to stories", exact: true })
.click();
await page.reload();
await expect(
page
.locator(".post-card")
.filter({ has: story(page) })
.getByText("Read", { exact: true }),
).toBeVisible();
expect(
await page.evaluate((key) => localStorage.getItem(key), legacyStorageKey),
).toBe("{broken JSON");
});
test("shows API failures and recovers when the user retries", async ({
page,
}) => {
const state = await mockReader(page);
state.failPosts = true;
await page.goto("/");
await expect(page.getByRole("alert")).toContainText(
"Collection temporarily unavailable.",
);
state.failPosts = false;
await page.getByRole("button", { name: "Try again", exact: true }).click();
await expect(story(page)).toBeVisible();
await expect(page.getByRole("alert")).toHaveCount(0);
});
test("sanitizes article markup while preserving safe content and keyboard navigation", async ({
page,
}) => {
await mockReader(page);
await page.goto("/");
const trigger = story(page);
await trigger.click();
const reader = page.getByRole("main", { name: "Article reader" });
await expect(reader).toBeVisible();
await expect(
reader.getByText("Collected article body with a safe link."),
).toBeVisible();
await expect(
reader.locator(
"script, iframe, form, input, .article-body button, .article-body [style], .article-body [id], [onerror]",
),
).toHaveCount(0);
await expect(reader.getByText("Unsafe link")).not.toHaveAttribute(
"href",
/javascript:/,
);
await expect(
reader.getByRole("link", { name: "Supporting story" }),
).toHaveAttribute("rel", "noopener noreferrer");
expect(
await page.evaluate(() => Reflect.get(window, "readerAttack")),
).toBeUndefined();
await expect(
reader.getByRole("button", { name: "Back to stories", exact: true }),
).toBeFocused();
await page.keyboard.press("Escape");
await expect(reader).toBeVisible();
await reader
.getByRole("button", { name: "Back to stories", exact: true })
.click();
await expect(reader).toHaveCount(0);
await expect(trigger).toBeFocused();
});
test("shows inline figures and credits at desktop and mobile widths", async ({
page,
}) => {
const state = await mockReader(page);
state.posts[0] = {
...article,
html: '<p>Before the illustration.</p><figure><img src="/assets/diagram.svg" alt="Article diagram"><figcaption>Screenshot credit: Example Lab</figcaption></figure><p>After the illustration.</p>',
};
await page.route("**/assets/diagram.svg", (route) =>
route.fulfill({
contentType: "image/svg+xml",
body: '<svg xmlns="http://www.w3.org/2000/svg" width="960" height="548"><rect width="960" height="548" fill="#eee"/><text x="30" y="70" fill="#111" font-size="32">Article diagram</text></svg>',
}),
);
await page.goto("/?article=shared-id&article_source=example.com");
for (const width of [1280, 390]) {
await page.setViewportSize({ width, height: 900 });
const figure = page.locator(".article-body figure");
const image = figure.getByRole("img", { name: "Article diagram" });
await image.scrollIntoViewIfNeeded();
await expect(image).toBeVisible();
await expect(figure.locator("figcaption")).toHaveText(
"Screenshot credit: Example Lab",
);
expect(
await image.evaluate((element: HTMLImageElement) => element.naturalWidth),
).toBe(960);
await expect(figure.locator("a")).toHaveAttribute(
"href",
/\/assets\/diagram.svg$/,
);
await expect(figure).toHaveCSS("margin-left", "0px");
await expectNoHorizontalOverflow(page);
}
});
test("supports mobile navigation and article reading without horizontal overflow", async ({
page,
}) => {
await page.setViewportSize({ width: 390, height: 844 });
await mockReader(page);
await page.goto("/");
await expect(story(page)).toBeVisible();
await expectNoHorizontalOverflow(page);
await page
.getByRole("button", { name: "Open navigation", exact: true })
.click();
const navigation = page.getByRole("navigation", { name: "Main navigation" });
await expect(navigation).toBeVisible();
await navigation
.getByRole("button", { name: "Sources", exact: true })
.click();
await expect(
page.getByRole("heading", { name: "Sources", exact: true }),
).toBeVisible();
await page
.getByRole("button", { name: "Open navigation", exact: true })
.click();
await navigation.getByRole("button", { name: "All", exact: true }).click();
await story(page).click();
await expect(
page.getByRole("main", { name: "Article reader" }),
).toBeVisible();
await expectNoHorizontalOverflow(page);
expect(
await page
.getByRole("main", { name: "Article reader" })
.evaluate((element) => element.scrollWidth <= element.clientWidth),
).toBe(true);
await page
.getByRole("button", { name: "Back to stories", exact: true })
.click();
await expect(page.getByRole("dialog")).toHaveCount(0);
await expectNoHorizontalOverflow(page);
});
test.describe("Phone reading", () => {
test.use({ isMobile: true, hasTouch: true });
for (const width of [320, 390]) {
test(`keeps navigation and reading controls reachable and restores the feed at ${width}px`, async ({
page,
}) => {
await page.setViewportSize({ width, height: 720 });
await mockReader(page);
await page.goto("/?view=stories");
const target = story(page, "Housing report 8");
await target.scrollIntoViewIfNeeded();
const feedScroll = await page.evaluate(() => window.scrollY);
expect(feedScroll).toBeGreaterThan(500);
const menu = page.getByRole("button", { name: "Open navigation" });
await expect(menu).toBeInViewport();
await target.tap();
await expect(
page.getByRole("main", { name: "Article reader" }),
).toBeVisible();
await page.evaluate(() => window.scrollTo(0, 950));
await expect.poll(() => page.evaluate(() => window.scrollY)).toBe(950);
await expect(menu).toBeInViewport();
const back = page.getByRole("button", {
name: "Back to stories",
exact: true,
});
await expect(back).toBeInViewport();
const header = await page.locator(".topbar").boundingBox();
const toolbar = await page.locator(".reader-toolbar").boundingBox();
expect(toolbar?.y).toBeGreaterThanOrEqual(
(header?.y ?? 0) + (header?.height ?? 0),
);
const larger = page.getByRole("button", { name: "Larger article text" });
for (const control of [menu, back, larger]) {
const box = await control.boundingBox();
expect(box?.width).toBeGreaterThanOrEqual(44);
expect(box?.height).toBeGreaterThanOrEqual(44);
}
await larger.tap();
await expect(page.locator(".article-body")).toHaveCSS(
"font-size",
"20px",
);
await expectNoHorizontalOverflow(page);
await back.tap();
await expect(target).toBeVisible();
await expect
.poll(() => page.evaluate(() => window.scrollY))
.toBe(feedScroll);
});
}
});