Skip to content
Myr

markdown.test.tsx

This file

Path

apps/web/test/markdown.test.tsx

380 lines · 12.5 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 1–8why, one step back
1import { describe, expect, it } from "@effect/vitest";
2import { CommitSha, ProjectName } from "@repo/protocol/ids";3import {4 RouterContextProvider,5 createMemoryHistory,6 createRootRoute,7 createRouter,8} from "@tanstack/react-router";

Merge fix/w12-reviewoscabrielbefore adoption7b8b393

line 9why, one step back
9import { Effect } from "effect";

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 10–17why, one step back
10import type { ReactElement } from "react";
11import { renderToString } from "react-dom/server";1213import {14 RepoMarkdown,15 RepoText,16 isMarkdownPath,17} from "../src/features/markdown/markdown.tsx";

Merge fix/w12-reviewoscabrielbefore adoption7b8b393

line 18why, one step back
18import { renderAt } from "./render.tsx";

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 19–21why, one step back
19
20const sha = CommitSha.make("0123456789abcdef0123456789abcdef01234567");21

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 22why, one step back
22const project = ProjectName.make("oscabriel/p");

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 23–54why, one step back
23
24const rendered = (source: string, dir = "") =>25 renderToString(26 <RepoMarkdown at={sha} dir={dir} project={project} source={source} />27 );2829const routed = (element: ReactElement, location = "/p") =>30 renderToString(31 <RouterContextProvider32 router={createRouter({33 history: createMemoryHistory({ initialEntries: [location] }),34 routeTree: createRootRoute(),35 })}36 >37 {element}38 </RouterContextProvider>39 );4041const anchorsOf = (markup: string) => markup.match(/<a\b[^>]*>/gu) ?? [];4243describe("what a README cannot carry", () => {44 it("drops a script and what it says", () => {45 const markup = rendered("before\n\n<script>alert(1)</script>\n\nafter");4647 expect(markup).not.toContain("script");48 expect(markup).not.toContain("alert");49 expect(markup).toContain("<p>after</p>");50 });5152 it("keeps an image but not its event handler", () => {53 const markup = rendered("<img src=x onerror=alert(1)>");54

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 55why, one step back
55 expect(markup).toContain(`src="/oscabriel/p/raw/${sha}/x"`);

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 56–81why, one step back
56 expect(markup).not.toContain("onerror");
57 expect(markup).not.toContain("alert");58 });5960 it.each([61 ["a javascript: link", "[x](javascript:alert(1))"],62 ["a data: link", '<a href="data:text/html,<b>hi</b>">x</a>'],63 ["a vbscript: link", "[x](vbscript:msgbox(1))"],64 ])("renders %s with no href", (_, source) => {65 const markup = rendered(source);6667 expect(anchorsOf(markup)).toStrictEqual(["<a>"]);68 expect(markup).not.toMatch(/javascript|data:|vbscript/u);69 });7071 it.each([72 ["an iframe", '<iframe src="https://e.org"></iframe>', "iframe"],73 ["a style", "<style>body{display:none}</style>", "<style"],74 ["a form", '<form action="/x"><input name="q"></form>', "action"],75 ])("drops %s", (_, source, word) => {76 const markup = rendered(`${source}\n\nafter`);7778 expect(markup).not.toContain(word);79 expect(markup).toContain("<p>after</p>");80 });81

Close the code browser and drafting wave: its decisions in two ADRs, every rule it added held, and its leftovers folded inoscabrielbefore adoption009640c

lines 82–88why, one step back
82 it("drops a style's CSS with the element, so no stray rules show as text", () => {
83 const markup = rendered("<style>body{display:none}</style>\n\nafter");8485 expect(markup).not.toContain("display:none");86 expect(markup).toContain("<p>after</p>");87 });88

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 89–101why, one step back
89 it("prefixes a name the README sets, so it cannot clobber the page's own", () => {
90 const markup = rendered('<a name="top">Top</a>');9192 expect(markup).toMatch(/(?:id|name)="user-content-top"/u);93 });94});9596const readme = (source: string) => rendered(source, "docs");9798describe("links and images in docs/README.md", () => {99 it("loads a relative image raw from the README's folder, at the SHA", () => {100 const markup = readme("![logo](./img/logo.png)");101

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 102why, one step back
102 expect(markup).toContain(`src="/oscabriel/p/raw/${sha}/docs/img/logo.png"`);

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 103–108why, one step back
103 expect(markup).toContain('loading="lazy"');
104 expect(markup).toContain('decoding="async"');105 expect(markup).toContain('referrerPolicy="no-referrer"');106 });107108 it.each([

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

lines 109–111why, one step back
109 ["[a](../../x)", `/oscabriel/p/blob/${sha}/x`],
110 ["[b](/LICENSE)", `/oscabriel/p/blob/${sha}/LICENSE`],111 ["[g](guide.md#install)", `/oscabriel/p/blob/${sha}/docs/guide.md#install`],

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 112–126why, one step back
112 ])("opens %s inside the project", (source, href) => {
113 expect(anchorsOf(readme(source))).toStrictEqual([`<a href="${href}">`]);114 });115116 it("opens a link inside the project through the router when there is one", () => {117 const markup = routed(118 <RepoMarkdown119 at={sha}120 dir="docs"121 project={project}122 source="[a](../../x?raw=1#L3)"123 />124 );125126 expect(anchorsOf(markup)).toStrictEqual([

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 127why, one step back
127 `<a href="/oscabriel/p/blob/${sha}/x?raw=1#L3">`,

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 128–138why, one step back
128 ]);
129 });130131 it("marks a link to the page it is on as the current page, its query and fragment read as such", () => {132 const markup = routed(133 <RepoMarkdown134 at={sha}135 dir="docs"136 project={project}137 source="[a](../../x?raw=1#L3)"138 />,

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 139why, one step back
139 `/oscabriel/p/blob/${sha}/x?raw=1#L3`

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 140–143why, one step back
140 );
141142 const [anchor] = anchorsOf(markup);143

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 144why, one step back
144 expect(anchor).toContain(`href="/oscabriel/p/blob/${sha}/x?raw=1#L3"`);

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 145–146why, one step back
145 expect(anchor).toContain('aria-current="page"');
146 });

Merge fix/w12-reviewoscabrielbefore adoption7b8b393

lines 147–160why, one step back
147
148 // A file's path may hold the router's own marks (`routes/$project/…`,149 // `bin/$.sh`): they are the file's name, never a param the router fills150 // from the page being read.151 it.effect(152 "opens a path holding $ or braces as the README names it, inside the app's router",153 () =>154 Effect.gen(function* () {155 const markup = yield* renderAt(156 "/p",157 <RepoMarkdown158 at={sha}159 dir=""160 project={project}

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 161why, one step back
161 source="[r](src/routes/$owner/$project/index.tsx) [s](bin/$.sh) [o](src/{-$x}.ts#L2)"

Merge fix/w12-reviewoscabrielbefore adoption7b8b393

lines 162–171why, one step back
162 />
163 );164165 expect(166 anchorsOf(markup).map((anchor) =>167 decodeURIComponent(168 /href="(?<href>[^"]*)"/u.exec(anchor)?.groups?.href ?? ""169 )170 )171 ).toStrictEqual([

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

lines 172–174why, one step back
172 `/oscabriel/p/blob/${sha}/src/routes/$owner/$project/index.tsx`,
173 `/oscabriel/p/blob/${sha}/bin/$.sh`,174 `/oscabriel/p/blob/${sha}/src/{-$x}.ts#L2`,

Merge fix/w12-reviewoscabrielbefore adoption7b8b393

lines 175–177why, one step back
175 ]);
176 })177 );

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 178–198why, one step back
178
179 it("leaves an external link as written, opened with no referrer", () => {180 const [anchor] = anchorsOf(readme("[c](https://e.org)"));181182 expect(anchor).toContain('href="https://e.org"');183 expect(anchor).toMatch(/rel="[^"]*\bnoopener\b[^"]*"/u);184 expect(anchor).toMatch(/rel="[^"]*\bnofollow\b[^"]*"/u);185 expect(anchor).toMatch(/rel="[^"]*\bnoreferrer\b[^"]*"/u);186 });187188 it("leaves a link to a heading as written", () => {189 expect(anchorsOf(readme("[d](#usage)"))).toStrictEqual([190 '<a href="#usage">',191 ]);192 });193194 it("resolves an image in the README's own HTML, as ky's and awesome's are written", () => {195 const markup = rendered(196 '<p align="center"><img src="media/logo.svg" width="200" alt="logo"></p>'197 );198

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 199why, one step back
199 expect(markup).toContain(`src="/oscabriel/p/raw/${sha}/media/logo.svg"`);

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 200–208why, one step back
200 expect(markup).toContain('align="center"');
201 });202203 it("resolves a picture's sources too, so the dark logo loads", () => {204 const markup = rendered(205 '<picture><source media="(prefers-color-scheme: dark)" srcset="media/dark.svg 1x, media/dark@2x.svg 2x"><img src="media/logo.svg"></picture>'206 );207208 expect(markup).toContain(

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 209why, one step back
209 `srcSet="/oscabriel/p/raw/${sha}/media/dark.svg 1x, /oscabriel/p/raw/${sha}/media/dark@2x.svg 2x"`

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

line 210why, one step back
210 );

Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8

line 211why, one step back
211 expect(markup).toContain(`src="/oscabriel/p/raw/${sha}/media/logo.svg"`);

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 212–231why, one step back
212 });
213});214215describe("GitHub-flavoured Markdown", () => {216 it("renders a table", () => {217 const markup = rendered("| a | b |\n| - | - |\n| 1 | 2 |");218219 expect(markup).toContain("<table>");220 expect(markup).toContain("<td>1</td>");221 });222223 it("renders a task list with checkboxes nobody can tick", () => {224 const markup = rendered("- [x] done\n- [ ] not yet");225226 expect(markup.match(/<input[^>]*>/gu)).toStrictEqual([227 '<input type="checkbox" disabled="" checked=""/>',228 '<input type="checkbox" disabled=""/>',229 ]);230 });231

Merge redesign into mainoscabrielbefore adoptioncaedd21

lines 232–234why, one step back
232 // A README sits under the project's own h1, so its levels go down by one.
233 it("gives a heading an id a link can point at, a level under the page's h1", () => {234 expect(rendered("## Hello World")).toContain('<h3 id="hello-world">');

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 235–236why, one step back
235 });
236

Merge redesign into mainoscabrielbefore adoptioncaedd21

lines 237–244why, one step back
237 it("draws no h1 of its own, and keeps an h6 an h6", () => {
238 const markup = rendered("# burrow\n\n###### Small");239240 expect(markup).not.toContain("<h1");241 expect(markup).toContain('<h2 id="burrow">');242 expect(markup).toContain('<h6 id="small">');243 });244

Merge build/1005oscabrielbefore adoptionb124cbb

lines 245–298why, one step back
245 describe("a footnote", () => {
246 const markup = rendered("Text[^1]\n\n[^1]: Note.");247248 const targetOf = (attribute: string) =>249 anchorsOf(markup)250 .find((anchor) => anchor.includes(attribute))251 ?.match(/href="#(?<id>[^"]+)"/u)?.groups?.id;252253 const idOf = (attribute: string) =>254 new RegExp(`<[a-z]+\\b[^>]*${attribute}[^>]*>`, "u")255 .exec(markup)?.[0]256 .match(/\bid="(?<id>[^"]+)"/u)?.groups?.id;257258 it("is referenced by a link that jumps to it", () => {259 const target = targetOf("data-footnote-ref");260261 expect(target).toBeDefined();262 expect(markup).toContain(`<li id="${target}">`);263 });264265 it("links back to its reference", () => {266 const back = targetOf("data-footnote-backref");267268 expect(back).toBeDefined();269 expect(back).toBe(idOf("data-footnote-ref"));270 });271272 it("keeps its ids prefixed once, as a README's own are", () => {273 expect(idOf("data-footnote-ref")).toBe("user-content-fnref-1");274 expect(markup).not.toContain("user-content-user-content-");275 });276 });277278 it("prefixes an id the README sets, and points a link to it there", () => {279 const markup = rendered('<a id="top">Top</a>\n\n[up](#top)');280281 expect(markup).toContain('id="user-content-top"');282 expect(markup).not.toContain('id="top"');283 expect(anchorsOf(markup)).toContain('<a href="#user-content-top">');284 });285286 it("prefixes an anchor's name the README sets, and points a link to it there", () => {287 const markup = rendered('<a name="top">Top</a>\n\n[up](#top)');288289 expect(markup).toContain('name="user-content-top"');290 expect(anchorsOf(markup)).toContain('<a href="#user-content-top">');291 });292293 it("keeps a link to a heading pointing at the heading", () => {294 const markup = rendered("## Usage\n\n[u](#usage)");295296 expect(anchorsOf(markup)).toContain('<a href="#usage">');297 });298

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 299–310why, one step back
299 it("keeps a code block's language and draws it in mono", () => {
300 const markup = rendered("```ts\nconst a = 1;\n```");301302 expect(markup).toContain('class="language-ts"');303 expect(markup).toContain("<pre");304 });305306 it("styles the whole as prose", () => {307 expect(rendered("hi")).toMatch(/class="[^"]*\bprose\b[^"]*"/u);308 });309});310

Draw text, controls, prose and code from one set of tokensoscabrielbefore adoption60f862e

lines 311–338why, one step back
311const proseClasses = () => {
312 const markup = rendered(313 "# datekit\n\nCall `format()` first.\n\n```ts\nconst a = () => 1;\n```"314 );315316 return new Set(317 /<div class="(?<classes>[^"]*\bprose\b[^"]*)"/u318 .exec(markup)319 ?.groups?.classes?.split(" ")320 );321};322323describe("a README drawn in the page's own type", () => {324 it("shows inline code without the backticks around it", () => {325 const classes = proseClasses();326327 expect(classes.has("prose-code:before:content-none")).toBeTruthy();328 expect(classes.has("prose-code:after:content-none")).toBeTruthy();329 });330331 it("sets a code block on the surface, ruled in a hairline, in the mono size", () => {332 const classes = proseClasses();333334 expect(classes.has("prose-pre:bg-surface")).toBeTruthy();335 expect(classes.has("prose-pre:border-rule")).toBeTruthy();336 expect(classes.has("prose-pre:text-mono")).toBeTruthy();337 });338

Merge redesign into mainoscabrielbefore adoptioncaedd21

lines 339–341why, one step back
339 // `--measure` is 72ch, which design-rules.test.tsx holds against DESIGN.md.
340 it("keeps lines to the measure", () => {341 expect(proseClasses().has("max-w-(--measure)")).toBeTruthy();

Draw text, controls, prose and code from one set of tokensoscabrielbefore adoption60f862e

lines 342–343why, one step back
342 });
343

Merge redesign into mainoscabrielbefore adoptioncaedd21

lines 344–346why, one step back
344 // Its `#` is an h2 by then (`rehypeShiftHeadings`), under the page's own h1.
345 it("sets its top heading at the title size, under the page's own headline", () => {346 expect(proseClasses().has("prose-h2:text-title")).toBeTruthy();

Draw text, controls, prose and code from one set of tokensoscabrielbefore adoption60f862e

lines 347–348why, one step back
347 });
348

Review fixes for 1201oscabrielbefore adoptionadc0bb1

lines 349–354why, one step back
349 it("sizes every element from the type scale, never an arbitrary size", () => {
350 expect(351 [...proseClasses()].filter((name) => /(?:^|:)text-\[/u.test(name))352 ).toStrictEqual([]);353 });354

Draw text, controls, prose and code from one set of tokensoscabrielbefore adoption60f862e

lines 355–362why, one step back
355 it("colours it from the tokens, so both schemes come from one set of classes", () => {
356 const classes = proseClasses();357358 expect(classes.has("prose-tokens")).toBeTruthy();359 expect(classes.has("dark:prose-invert")).toBeFalsy();360 });361});362

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 363–380why, one step back
363describe("a README that is not Markdown", () => {
364 it.each([365 ["README.md", true],366 ["docs/readme.markdown", true],367 ["README.mdown", true],368 ["README", false],369 ["README.txt", false],370 ["README.rst", false],371 ])("reads %s as Markdown: %s", (path, markdown) => {372 expect(isMarkdownPath(path)).toBe(markdown);373 });374375 it("shows as written, in a pre", () => {376 const markup = renderToString(<RepoText source={"# not a heading\n<b>"} />);377378 expect(markup).toMatch(/^<pre[^>]*># not a heading\n&lt;b&gt;<\/pre>$/u);379 });380});