Skip to content
Myr

shell.test.tsx

This file

Path

apps/web/test/shell.test.tsx

651 lines · 19.4 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

1import { describe, expect, it } from "@effect/vitest";2import { docEntries } from "@repo/agent-kit/docs/entries";3import { Brand } from "@repo/brand";4import { ProjectName } from "@repo/protocol/ids";5import {6  createMemoryHistory,7  createRootRoute,8  createRoute,9  createRouter,10  Outlet,11  RouterProvider,12  useParams,13} from "@tanstack/react-router";14import type { StaticDataRouteOption } from "@tanstack/react-router";15import { Effect } from "effect";16import type { ReactNode } from "react";17import { renderToStaticMarkup } from "react-dom/server";1819import { useKeys } from "../src/features/shared/keys.tsx";20import { PageShell } from "../src/features/shared/layout.tsx";21import { AppLink } from "../src/features/shared/link.tsx";22import { projectPath } from "../src/features/shared/paths.ts";23import { RouteError } from "../src/features/shared/pending.tsx";24import { AppShell } from "../src/features/shared/shell/app-shell.tsx";25import {26  MenuBody,27  ProjectsSheetBody,28} from "../src/features/shared/shell/overlays.tsx";29import { SITE_LINKS } from "../src/features/shared/shell/top-bar.tsx";30import { Workspace } from "../src/features/shared/shell/workspace.tsx";31import { Route as projectRoute } from "../src/routes/$owner/$project/route.tsx";32import { Route as docsRoute } from "../src/routes/docs/$page.tsx";33import { Route as importRoute } from "../src/routes/import.tsx";34import { Route as landingRoute } from "../src/routes/index.tsx";35import { TEN_LISTED } from "./listings.ts";36import { renderAt } from "./render.tsx";3738const elementOf = (markup: string, tag: string, attribute: string) =>39  new RegExp(`<${tag}\\b[^>]*${attribute}[^>]*>[\\s\\S]*?</${tag}>`, "u").exec(40    markup41  )?.[0] ?? "";4243const linksOf = (markup: string) =>44  [...markup.matchAll(/<a\b(?<attributes>[^>]*)>(?<text>[\s\S]*?)<\/a>/gu)].map(45    ({ groups }) => {46      const attributes = groups?.attributes ?? "";4748      return {49        active: /data-status="active"/u.test(attributes),50        current: /aria-current="page"/u.exec(attributes) !== null,51        href: /href="(?<href>[^"]*)"/u.exec(attributes)?.groups?.href,52        text: (groups?.text ?? "")53          .replaceAll(/<[^>]+>/gu, " ")54          .replaceAll(/\s+/gu, " ")55          .trim(),56      };57    }58  );5960const textOf = (markup: string) =>61  markup62    .replaceAll(/<[^>]+>/gu, " ")63    .replaceAll(/\s+/gu, " ")64    .trim();6566/** The opening tag of the first element carrying the attribute. */67const tagWith = (markup: string, attribute: string) =>68  new RegExp(`<[a-z]+\\b[^>]*${attribute}[^>]*>`, "u").exec(markup)?.[0] ?? "";6970const shellOf = (staticData: StaticDataRouteOption | undefined) =>71  staticData?.shell;7273const staticOf = (route: {74  readonly options: { readonly staticData?: StaticDataRouteOption };75}): StaticDataRouteOption => route.options.staticData ?? {};7677/**78 * One route per shell, each carrying the `staticData` its real route79 * declares, so the frame drawn is the one the route names.80 */81const shellRoutes = (view: ReactNode) => {82  const root = createRootRoute({83    component: () => (84      <AppShell>85        <Outlet />86      </AppShell>87    ),88  });8990  const page = () => view;9192  return root.addChildren([93    createRoute({94      component: page,95      getParentRoute: () => root,96      path: "/",97      staticData: staticOf(landingRoute),98    }),99    createRoute({100      component: page,101      getParentRoute: () => root,102      path: "$owner/$project",103      staticData: staticOf(projectRoute),104    }),105    createRoute({106      component: page,107      getParentRoute: () => root,108      path: "docs/$page",109      staticData: staticOf(docsRoute),110    }),111    createRoute({112      component: page,113      getParentRoute: () => root,114      path: "import",115      staticData: staticOf(importRoute),116    }),117  ]);118};119120const inShell = (121  url: string,122  view: ReactNode = (123    <PageShell title="Page">124      <p>Body</p>125    </PageShell>126  )127) =>128  Effect.gen(function* () {129    const router = createRouter({130      history: createMemoryHistory({ initialEntries: [url] }),131      routeTree: shellRoutes(view),132    });133134    yield* Effect.tryPromise(() => router.load());135136    return renderToStaticMarkup(<RouterProvider router={router} />);137  });138139const SITE = "/";140141const PROJECT = "/oscabriel/datekit";142143const DOCS = "/docs/answer-an-ask";144145const FOCUS = "/import";146147const topBarOf = (markup: string) =>148  elementOf(markup, "header", "data-top-bar");149150const KeysProbe = () => (151  <p data-keys={useKeys() === undefined ? "missing" : "provided"}>Keys</p>152);153154describe("the four shells", () => {155  it("are what the real routes name", () => {156    expect(157      [landingRoute, projectRoute, docsRoute, importRoute].map(({ options }) =>158        shellOf(options.staticData)159      )160    ).toStrictEqual(["site", "project", "docs", "focus"]);161  });162163  it.effect(164    "draw the site with the framed top bar and the footer, and no side column",165    () =>166      Effect.gen(function* () {167        const markup = yield* inShell(SITE);168169        expect(tagWith(markup, "data-shell=")).toContain('data-shell="site"');170        expect(tagWith(markup, "data-top-bar")).toContain(171          'data-top-bar="framed"'172        );173        expect(elementOf(markup, "footer", "data-footer")).not.toBe("");174        expect(markup).not.toContain("<aside");175        expect(markup).not.toContain("data-column");176      })177  );178179  it.effect("draw a project with the full-bleed top bar and no footer", () =>180    Effect.gen(function* () {181      const markup = yield* inShell(PROJECT);182183      expect(tagWith(markup, "data-shell=")).toContain('data-shell="project"');184      expect(tagWith(markup, "data-top-bar")).toContain(185        'data-top-bar="full-bleed"'186      );187      expect(markup).not.toContain("<footer");188    })189  );190191  it.effect(192    "draw the docs with a nav tree of every page, the page being read current, and the footer",193    () =>194      Effect.gen(function* () {195        const markup = yield* inShell(DOCS);196        const tree = linksOf(elementOf(markup, "nav", 'aria-label="Docs"'));197198        expect(tagWith(markup, "data-shell=")).toContain('data-shell="docs"');199        expect(tree.map(({ href }) => href)).toStrictEqual(200          docEntries.map(({ slug }) => `/docs/${slug}`)201        );202        expect(203          tree.filter(({ current }) => current).map(({ text }) => text)204        ).toStrictEqual(["Answer an ask"]);205        expect(elementOf(markup, "footer", "data-footer")).not.toBe("");206      })207  );208209  it.effect(210    "draw a focused page with the wordmark alone and no navigation",211    () =>212      Effect.gen(function* () {213        const markup = yield* inShell(FOCUS);214215        expect(tagWith(markup, "data-shell=")).toContain('data-shell="focus"');216        expect(linksOf(topBarOf(markup))).toStrictEqual([217          { active: false, current: false, href: "/", text: Brand.name },218        ]);219        expect(markup).not.toContain("<nav");220        expect(markup).not.toContain("<footer");221      })222  );223224  it.effect(225    "draw no route with the old rail, its slot, the bottom bar or the inspector",226    () =>227      Effect.gen(function* () {228        const markups = [229          yield* inShell(SITE),230          yield* inShell(PROJECT),231          yield* inShell(DOCS),232          yield* inShell(FOCUS),233        ].join("\n");234235        expect(markups).not.toMatch(/\bdata-rail(?:-slot)?\b/u);236        expect(markups).not.toContain('aria-label="Site"');237        expect(markups).not.toContain('aria-label="Sections"');238        expect(markups).not.toContain('data-facts="inspector"');239        expect(markups).not.toMatch(/>Menu</u);240      })241  );242});243244describe("the top bar", () => {245  const NAMED = [246    { href: "/", text: Brand.name },247    { href: "/explore", text: "Explore" },248    { href: "/asks", text: "Asks" },249    { href: "/docs", text: "Docs" },250    { href: "/install", text: "Install" },251  ];252253  it.effect(254    "is the same in the site, a project and the docs: the wordmark, Explore, Asks, Docs, Install, search and the account",255    () =>256      Effect.gen(function* () {257        const bars = [258          topBarOf(yield* inShell(SITE)),259          topBarOf(yield* inShell(PROJECT)),260          topBarOf(yield* inShell(DOCS)),261        ];262263        const named = bars.map((bar) =>264          linksOf(bar)265            .filter(({ href }) => href?.startsWith("/auth/") !== true)266            .map(({ href, text }) => ({ href, text }))267        );268269        expect(named).toStrictEqual([NAMED, NAMED, NAMED]);270        expect(271          bars.map((bar) => /<button\b[^>]*>[\s\S]*?Search/u.test(bar))272        ).toStrictEqual([true, true, true]);273        expect(274          bars.map((bar) =>275            linksOf(bar).some(276              ({ href, text }) =>277                href?.startsWith("/auth/signin") === true && text === "Sign in"278            )279          )280        ).toStrictEqual([true, true, true]);281      })282  );283284  it.effect("sets the wordmark as the name in text, with no mark", () =>285    Effect.gen(function* () {286      const bar = topBarOf(yield* inShell(SITE));287      const wordmark = elementOf(bar, "a", 'href="/"');288289      expect(textOf(wordmark)).toBe(Brand.name);290      expect(wordmark).not.toMatch(/<svg|<img/u);291    })292  );293294  // A colour given to a kit button must not cost it the UI size: the295  // class merger reads an unknown `text-*` as a colour, so a colour class296  // drops `text-ui` and the button falls back to the body's 16 px.297  it.effect("sets every button in it at the UI size", () =>298    Effect.gen(function* () {299      const buttons = [300        ...topBarOf(yield* inShell(PROJECT)).matchAll(301          /<button\b[^>]*class="(?<classes>[^"]*)"/gu302        ),303      ].map(({ groups }) => groups?.classes?.split(" ") ?? []);304305      expect(buttons.length).toBeGreaterThanOrEqual(2);306      expect(307        buttons.filter((classes) => !classes.includes("text-ui"))308      ).toStrictEqual([]);309    })310  );311312  // The menu's button is `nav:hidden`, and the menu holds Keys; from `nav` up313  // this button is the `?` key's pointer twin.314  it.effect(315    "gives the keys a button in the site, a project and the docs, shown from nav up",316    () =>317      Effect.gen(function* () {318        const keys = [319          topBarOf(yield* inShell(SITE)),320          topBarOf(yield* inShell(PROJECT)),321          topBarOf(yield* inShell(DOCS)),322        ].map(323          (bar) =>324            /<span class="(?<wrap>[^"]*)"><button\b[^>]*>(?:(?!<\/button>)[\s\S])*?>Keys<\/span><\/button>/u325              .exec(bar)326              ?.groups?.wrap?.split(" ") ?? []327        );328329        expect(330          keys.map((classes) => classes.includes("nav:flex"))331        ).toStrictEqual([true, true, true]);332      })333  );334335  it.effect("marks the section being read as the current page", () =>336    Effect.gen(function* () {337      const bar = topBarOf(yield* inShell(DOCS));338339      expect(340        linksOf(bar)341          .filter(({ active }) => active)342          .map(({ href }) => href)343      ).toStrictEqual(["/docs"]);344    })345  );346});347348describe("the footer", () => {349  it.effect(350    "sets the brand's domain across the width, upper-cased by its style, under plain links",351    () =>352      Effect.gen(function* () {353        const footer = elementOf(yield* inShell(SITE), "footer", "data-footer");354        const domain = tagWith(footer, "data-domain");355356        expect(textOf(elementOf(footer, "p", "data-domain"))).toBe(357          Brand.domain358        );359        expect(domain.split(/[\s"]/u)).toContain("uppercase");360        expect(linksOf(footer).map(({ text }) => text)).toStrictEqual([361          "Docs",362          "Install",363          "Settings",364          "Privacy",365          "Terms",366        ]);367      })368  );369});370371describe("every shell", () => {372  it.effect("lets a keyboard skip to the page's content", () =>373    Effect.gen(function* () {374      const markups = [375        yield* inShell(SITE),376        yield* inShell(PROJECT),377        yield* inShell(DOCS),378        yield* inShell(FOCUS),379      ];380381      expect(382        markups.map((markup) =>383          /<a\b[^>]*href="#main"[^>]*>Skip to content<\/a>/u.test(markup)384        )385      ).toStrictEqual([true, true, true, true]);386    })387  );388389  it.effect(390    "keeps the keys, and `?` for their list, with no rail to hold them",391    () =>392      Effect.gen(function* () {393        const probes = [394          yield* inShell(SITE, <KeysProbe />),395          yield* inShell(PROJECT, <KeysProbe />),396          yield* inShell(DOCS, <KeysProbe />),397          yield* inShell(FOCUS, <KeysProbe />),398        ];399400        expect(401          probes.map((markup) => /data-keys="(?<keys>\w+)"/u.exec(markup)?.[1])402        ).toStrictEqual(["provided", "provided", "provided", "provided"]);403      })404  );405406  it.effect("gives the page one main region", () =>407    Effect.gen(function* () {408      const markups = [409        yield* inShell(SITE),410        yield* inShell(PROJECT),411        yield* inShell(DOCS),412        yield* inShell(FOCUS),413      ];414415      expect(416        markups.map((markup) => markup.split("<main").length - 1)417      ).toStrictEqual([1, 1, 1, 1]);418    })419  );420});421422describe("a page's facts", () => {423  it.effect("sit in the page itself, never in a column beside it", () =>424    Effect.gen(function* () {425      const markup = yield* inShell(426        PROJECT,427        <Workspace428          facts={<p>Posture: open</p>}429          factsHeading="This ledger"430          title="Ledger"431        >432          <p>Entries</p>433        </Workspace>434      );435436      const main = elementOf(markup, "main", 'id="main"');437438      expect(elementOf(main, "section", 'data-facts="inline"')).toContain(439        "Posture: open"440      );441      expect(markup).not.toContain("<aside");442    })443  );444445  it.effect("name no breadcrumb in a focused page", () =>446    Effect.gen(function* () {447      const markup = yield* inShell(448        FOCUS,449        <Workspace crumbs={[{ label: "Import a repo" }]} title="Import a repo">450          <p>Form</p>451        </Workspace>452      );453454      expect(markup).not.toContain('aria-label="Breadcrumb"');455    })456  );457});458459describe("the search", () => {460  it.effect(461    "lists every project by its full name, and ends with the way to import a repo",462    () =>463      Effect.gen(function* () {464        const markup = yield* renderAt(465          "/install",466          <ProjectsSheetBody467            input={{ current: null }}468            listed={TEN_LISTED}469            onChosen={() => {}}470          />471        );472473        expect(474          TEN_LISTED.filter(({ project }) => !markup.includes(`>${project}<`))475        ).toStrictEqual([]);476        expect(linksOf(markup).at(-1)).toMatchObject({477          href: "/import",478          text: "Import a repo",479        });480      })481  );482});483484describe("the menu", () => {485  it.effect(486    "folds the top bar's links below nav, in its order, and opens the keys",487    () =>488      Effect.gen(function* () {489        const markup = yield* renderAt("/install", <MenuBody />);490491        expect(492          linksOf(markup).map(({ href, text }) => ({ href, text }))493        ).toStrictEqual(494          SITE_LINKS.map(({ label, to }) => ({ href: to, text: label }))495        );496        expect(markup).toMatch(/<button\b[^>]*>[\s\S]*?Keys<\/button>/u);497      })498  );499});500501const ProjectParamsView = () => {502  const { owner, project } = useParams({ strict: false });503504  return (505    <p data-owner={owner} data-project={project}>506      <AppLink507        to={`${projectPath(ProjectName.make("github.com/pallets/click"))}/tree/main`}508      >509        tree510      </AppLink>511    </p>512  );513};514515describe("a project at its source path", () => {516  it.effect(517    "reaches the project's pages with its owner in one param, and links back to the same address",518    () =>519      Effect.gen(function* () {520        const markup = yield* renderAt(521          "/github.com/pallets/click/tree/main",522          <ProjectParamsView />523        );524525        expect(markup).toContain('data-owner="github.com/pallets"');526        expect(markup).toContain('data-project="github.com/pallets/click"');527        expect(linksOf(markup).map(({ href }) => href)).toStrictEqual([528          "/github.com/pallets/click/tree/main",529        ]);530      })531  );532});533534describe(AppLink, () => {535  // A path is built whole, and a file's path may hold the router's own536  // marks (`routes/$project/route.tsx`, `{-$x}`): they are the file's537  // name, never a param to fill from the page being read.538  it.effect("leads to a path holding $ or braces as written", () =>539    Effect.gen(function* () {540      const markup = yield* renderAt(541        "/oscabriel/datekit/visibility",542        <p>543          <AppLink to="/oscabriel/datekit/blob/main/src/routes/$owner/$project/$.tsx">544            route545          </AppLink>546          <AppLink to="/oscabriel/datekit/blob/main/src/{-$x}.ts">547            optional548          </AppLink>549        </p>550      );551552      const hrefs = linksOf(markup).map(({ href }) => href);553554      expect(hrefs.map((href) => decodeURIComponent(href ?? ""))).toStrictEqual(555        [556          "/oscabriel/datekit/blob/main/src/routes/$owner/$project/$.tsx",557          "/oscabriel/datekit/blob/main/src/{-$x}.ts",558        ]559      );560    })561  );562563  it("draws the same address with no router around it", () => {564    expect(565      renderToStaticMarkup(566        <AppLink to="/oscabriel/datekit/blob/main/src/routes/$owner/$project/$.tsx">567          route568        </AppLink>569      )570    ).toMatch(571      /href="\/oscabriel\/datekit\/blob\/main\/src\/routes\/(?:\$|%24)owner\/(?:\$|%24)project\/(?:\$|%24)\.tsx"/u572    );573  });574});575576describe("the shell's sources", () => {577  // Keys only: the sources as text.578  const sources: Readonly<Record<string, string>> = import.meta.glob(579    "../src/features/shared/shell/*.tsx",580    { eager: true, import: "default", query: "?raw" }581  );582583  it("draw no plain anchor: every link is the router's, so a click never reloads the document", () => {584    expect(Object.keys(sources).length).toBeGreaterThan(3);585    expect(586      Object.entries(sources).flatMap(([file, source]) =>587        /<a\b/u.test(source) ? [file] : []588      )589    ).toStrictEqual([]);590  });591});592593describe(PageShell, () => {594  it.effect("gives a page one main region headed by its title", () =>595    Effect.gen(function* () {596      const markup = yield* renderAt(597        "/inbox",598        <PageShell title="Inbox">599          <p>Decisions 2 of 5</p>600        </PageShell>601      );602603      expect(elementOf(markup, "main", 'id="main"')).toMatch(604        /<h1\b[^>]*>Inbox<\/h1>[\s\S]*<p>Decisions 2 of 5<\/p>/u605      );606    })607  );608});609610describe("a page whose read fails", () => {611  // A transport failure is not a refusal: ink and a way to ask again,612  // inside the shell, never the router's own error page.613  it.effect("says the platform did not answer, in ink, inside the shell", () =>614    Effect.gen(function* () {615      const root = createRootRoute({616        component: () => (617          <AppShell>618            <Outlet />619          </AppShell>620        ),621      });622623      const failing = createRoute({624        getParentRoute: () => root,625        loader: () => Promise.reject(new Error("fetch failed")),626        path: "$owner/$project",627      });628629      const router = createRouter({630        defaultErrorComponent: RouteError,631        history: createMemoryHistory({632          initialEntries: ["/oscabriel/datekit"],633        }),634        routeTree: root.addChildren([failing]),635      });636637      yield* Effect.tryPromise(() => router.load());638639      const markup = renderToStaticMarkup(<RouterProvider router={router} />);640      const main = elementOf(markup, "main", 'id="main"');641642      expect(textOf(main)).toContain("The platform did not answer.");643      expect(textOf(main)).toContain(644        "Try again in a minute; nothing was changed."645      );646      expect(main).toMatch(/<button\b[^>]*>Reload<\/button>/u);647      expect(main).not.toContain("refused");648      expect(markup).toContain("data-top-bar");649    })650  );651});