netjes 0.0.4 → 0.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -8
- package/cli/commands.mjs +94 -15
- package/cli/process-io.mjs +2 -2
- package/cli/scaffold.mjs +89 -8
- package/dist/actions.d.ts +3 -2
- package/dist/actions.d.ts.map +1 -1
- package/dist/actions.js +5 -4
- package/dist/actions.js.map +1 -1
- package/dist/client-entry.js +4 -1
- package/dist/client-entry.js.map +1 -1
- package/dist/document.d.ts +3 -1
- package/dist/document.d.ts.map +1 -1
- package/dist/document.js +4 -3
- package/dist/document.js.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/lang.d.ts +10 -0
- package/dist/lang.d.ts.map +1 -0
- package/dist/lang.js +26 -0
- package/dist/lang.js.map +1 -0
- package/dist/link.d.ts +15 -3
- package/dist/link.d.ts.map +1 -1
- package/dist/link.js +15 -9
- package/dist/link.js.map +1 -1
- package/dist/locale.d.ts +5 -0
- package/dist/locale.d.ts.map +1 -1
- package/dist/locale.js +4 -0
- package/dist/locale.js.map +1 -1
- package/dist/metadata.d.ts +81 -4
- package/dist/metadata.d.ts.map +1 -1
- package/dist/metadata.js +129 -7
- package/dist/metadata.js.map +1 -1
- package/dist/modules.d.ts +6 -1
- package/dist/modules.d.ts.map +1 -1
- package/dist/modules.js +15 -1
- package/dist/modules.js.map +1 -1
- package/dist/mounted.d.ts +3 -7
- package/dist/mounted.d.ts.map +1 -1
- package/dist/mounted.js.map +1 -1
- package/dist/navigation-guard.d.ts +59 -0
- package/dist/navigation-guard.d.ts.map +1 -0
- package/dist/navigation-guard.js +116 -0
- package/dist/navigation-guard.js.map +1 -0
- package/dist/offline.d.ts +11 -0
- package/dist/offline.d.ts.map +1 -0
- package/dist/offline.js +98 -0
- package/dist/offline.js.map +1 -0
- package/dist/payload.d.ts +38 -2
- package/dist/payload.d.ts.map +1 -1
- package/dist/payload.js +54 -7
- package/dist/payload.js.map +1 -1
- package/dist/render-document.d.ts +8 -1
- package/dist/render-document.d.ts.map +1 -1
- package/dist/render-document.js +2 -0
- package/dist/render-document.js.map +1 -1
- package/dist/root.d.ts.map +1 -1
- package/dist/root.js +10 -1
- package/dist/root.js.map +1 -1
- package/dist/route-tree.d.ts +2 -1
- package/dist/route-tree.d.ts.map +1 -1
- package/dist/route-tree.js +14 -7
- package/dist/route-tree.js.map +1 -1
- package/dist/router.d.ts +101 -20
- package/dist/router.d.ts.map +1 -1
- package/dist/router.js +590 -68
- package/dist/router.js.map +1 -1
- package/dist/schema.d.ts +2 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +5 -0
- package/dist/schema.js.map +1 -1
- package/dist/service-worker.d.ts +81 -0
- package/dist/service-worker.d.ts.map +1 -0
- package/dist/service-worker.js +584 -0
- package/dist/service-worker.js.map +1 -0
- package/dist/testing.d.ts +18 -0
- package/dist/testing.d.ts.map +1 -1
- package/dist/testing.js +63 -22
- package/dist/testing.js.map +1 -1
- package/package.json +16 -5
- package/sidecar/server.mjs +105 -16
- package/skills/netjes/SKILL.md +5 -3
- package/skills/netjes/references/caching-and-streaming.md +22 -1
- package/skills/netjes/references/data-and-actions.md +5 -4
- package/skills/netjes/references/deployment.md +3 -3
- package/skills/netjes/references/routing.md +14 -6
- package/skills/netjes/references/testing.md +6 -3
- package/src/actions.tsx +5 -4
- package/src/client-entry.tsx +4 -1
- package/src/document.tsx +17 -5
- package/src/index.ts +12 -2
- package/src/lang.ts +28 -0
- package/src/link.tsx +37 -9
- package/src/locale.ts +5 -0
- package/src/metadata.tsx +207 -11
- package/src/modules.ts +19 -3
- package/src/mounted.tsx +3 -3
- package/src/navigation-guard.ts +136 -0
- package/src/offline.ts +97 -0
- package/src/payload.ts +78 -8
- package/src/render-document.tsx +10 -1
- package/src/root.tsx +22 -10
- package/src/route-tree.tsx +18 -7
- package/src/router.tsx +765 -104
- package/src/schema.ts +11 -0
- package/src/service-worker.ts +632 -0
- package/src/testing-vitest.ts +1 -1
- package/src/testing.tsx +68 -15
- package/template/Dockerfile +1 -1
- package/template/Dockerfile.pnpm +68 -0
- package/template/Dockerfile.workspace +52 -0
- package/template/Dockerfile.workspace.dockerignore +15 -0
- package/template/README.md +6 -2
- package/template/_AGENTS.md +9 -3
- package/template/app/layout.tsx +0 -1
- package/template/docker-compose.override.yml +15 -3
- package/template/generated/netjes.ts +1 -1
- package/tsconfig.strict-app.json +27 -0
- package/vite/packages.mjs +97 -0
- package/vite/plugin.d.ts +8 -1
- package/vite/plugin.mjs +156 -9
- /package/template/{public/favicon.svg → app/icon.svg} +0 -0
|
@@ -14,6 +14,7 @@ ASP.NET Core does the routing: every page file becomes an endpoint with an ordin
|
|
|
14
14
|
| `not-found.tsx` | Rendered for `Page.NotFound()` from a loader below it, and the root one for unknown URLs, except below a page package's mount, where the package's renders. |
|
|
15
15
|
| `forbidden.tsx`, `unauthorized.tsx` | Rendered for `Page.Forbidden()` / `Page.Unauthorized()` and for empty 403/401 responses from authorization; without one, the error page renders. |
|
|
16
16
|
| `global-error.tsx` | In `app/` only: rendered without any layout when even the error page fails. |
|
|
17
|
+
| `favicon.ico`, `icon.svg` (`.png`, `.ico`, `.jpg`; `icon1.png` and on), `apple-icon.png` (and on), `manifest.webmanifest` | At the root of `app/` only: served at the site root and linked from every page (with a content hash, type and sizes, under the base path). Write no `<link>` tags or `metadata.icons` for them. The same name in `public/` stops the app; in a subfolder or a page package they are ignored with a route warning. |
|
|
17
18
|
|
|
18
19
|
Built-in pages stand in for missing boundary files.
|
|
19
20
|
|
|
@@ -47,24 +48,31 @@ ASP.NET Core ranks the endpoints a URL matches by order (pages and `MapGet` endp
|
|
|
47
48
|
|
|
48
49
|
- `<Link href={route('/blog/[slug]', { slug })}>`: client navigation with prefetch on hover and focus; takes a `ref`, as `<Form>`, `<SubmitButton>` and `<Image>` do. `route()` and the `Href` type come from `generated/netjes.ts`, so a wrong path or a missing parameter is a type error.
|
|
49
50
|
- `route(pattern, params, search, { hash })` builds the query from `search` and a `#fragment` from `hash`, the id of an element on the page: `route('/docs/[...path]', { path }, undefined, { hash: 'keys' })`. Pass `undefined` as `search` for a link with a fragment and no query.
|
|
50
|
-
- `aria-current="page"` goes on a link to the page on screen: the same path (`/x` and `/x/` are one) and the page's values for every query parameter the link names. Parameters it leaves out do not count, and a `#` link is never marked. Pass `aria-current` to decide yourself: `undefined` on an "All" filter (`/blog`) while a filter is on, `"true"` on a section link (Docs) below the section's page, from `useSelectedLayoutSegments()` or `usePathname()`.
|
|
51
|
+
- `aria-current="page"` goes on a link to the page on screen: the same path (`/x` and `/x/` are one) and the page's values for every query parameter the link names. Parameters it leaves out do not count (with `exactQuery`, they do: the page's query must be the link's, in any order, which a list's paging and sort links need, so Previous to page 1 is not marked on page 2), and a `#` link is never marked. Pass `aria-current` to decide yourself: `undefined` on an "All" filter (`/blog`) while a filter is on, `"true"` on a section link (Docs) below the section's page, from `useSelectedLayoutSegments()` or `usePathname()`.
|
|
51
52
|
- `useRouter()`: `push`, `replace`, `prefetch`, `refresh`, `back`, `forward`. The promises of `push`, `replace` and `refresh` resolve once the router has handed the page to React, when the old page can still be on screen; code that needs the new page runs in an effect of that page, or in one that depends on `usePathname()` and `useSearchParams()`.
|
|
52
53
|
- After a navigation to another page the router announces it in a polite live region (its title, else its first `h1`, else its path) and starts the focus over at the top of the document. A link to a `#fragment`, on the page on screen or on another, moves the focus to that element instead, which is how the skip link works; Back and Forward restore the scroll position and give a fragment no focus. The region speaks only when the name differs from the previous page's, so give each page its own title, and keep the skip link the first thing in the root layout that takes the focus: `<Link href="#content" prefetch="none" className="sr-only focus:not-sr-only">Skip to content</Link>` and `<main id="content">`. The focus stays on the same page (query changes, refreshes, a post that stays, a modal), on an `autoFocus` element or wherever the app's code moved it during the navigation (a link's `onClick` and a form's `onSubmit` included), on a `scroll={false}` link that still has it, and in a field the user types into. To put it elsewhere on the new page, do it in that page's `useEffect`, which runs after the router's. If a menu closes in an effect after the navigation, give the focus back to its button only while the focus is still inside the menu. In end-to-end tests, focus a field before typing after a navigation (`locator.fill()` does), and read the element you mean rather than a container's whole text.
|
|
53
54
|
- `usePathname()`, `useSearchParams(schema?)`, `useParams(schema?)`: with a schema the values are parsed; catch-all params are arrays. Search values a schema rejects are dropped so its defaults apply; a rejected route param goes to the error page, so constrain route params in C#.
|
|
54
55
|
- `useSelectedLayoutSegment()`, `useSelectedLayoutSegments()`: the active child segment in a layout (tabs).
|
|
55
|
-
- `useNavigation()`: `idle`, `loading` or `submitting`, for progress indicators.
|
|
56
|
+
- `useNavigation()`: `idle`, `loading` or `submitting`, for progress indicators. After a navigation, `refresh()` or a form post that got no page (no answer while the browser is online, or a server error that is no page), the page stays and `idle` carries `error: { kind: 'navigate' | 'refresh' | 'submit', status, location }` (`status` null for no answer; a post the server redirected went through, so a failure of the page it leads to is `'navigate'`) until the next one starts; show it in the app's shell, with Try again (`router.refresh()`) for a refresh. `refresh()` never rejects: read its failure here, not in a `catch`. An offline browser still loads the URL as a document.
|
|
57
|
+
- `useHistoryState(name, initial, schema?)`: `useState` kept with the history entry, through Back, Forward and a reload, for what a page keeps of a visit (a list's ticks, the list a record was opened from). `initial` on the server and while hydrating. A new entry starts from `initial` or from what its navigation carried (`historyState` on `<Link>`, `router.push(href, { historyState })`, `router.replace`); a navigation that keeps the page on screen (a query, a fragment, a refresh) keeps the values, one to another page starts over. The setter, like `useState`'s, keeps working, as the same function, while the page stays (`await deleteTicked(ticked); setTicked([])` clears the ticks after an action that refreshes the page), and sets nothing once the page has left or Back or Forward went to another entry. Small values `structuredClone` can copy (ids, not rows); a page package prefixes its names. A schema at module level turns a value it rejects into `initial`. `createTestApp({ historyState })` seeds them in a test.
|
|
58
|
+
- `useNavigationGuard({ when, onAttempt })`: while `when` holds (a form with changes not saved), links, `<Form method="get">`, `router.push`, `replace`, `back`, `forward` and the browser's Back and Forward wait for `onAttempt(attempt)` to call `attempt.proceed()` or `attempt.stay()`; the page draws the question (`attempt.to`, `attempt.type`). For Back and Forward the entry is put back first. Not held: a fragment of the page on screen, form posts, server actions, `refresh()`, other origins, and the page a redirect that answers a post, an action or a refresh leads to (the sign-in page after the session expired): keep a draft in `sessionStorage` where changes must outlast that. While it holds, `beforeunload` covers a reload and closing the tab. `proceed()` always works, also after the form saved and `when` turned false. Navigate with the router, not `history.pushState` or `location.replace`: the guard counts Back and Forward by the places the router writes into `history.state`.
|
|
59
|
+
- `useHistoryRestore(callback)`: called when Back or Forward shows the page from memory (the router's, or the browser's back-forward cache), as it was when left; `useHistoryRestore(() => void router.refresh())` for a page that must show what is current, such as a list after its record changed.
|
|
56
60
|
- External URLs, `target`, `download` and modified clicks behave like a plain `<a>`; `reloadDocument` forces a full load.
|
|
57
61
|
|
|
58
62
|
## Metadata
|
|
59
63
|
|
|
60
64
|
- `export const metadata: Metadata = { title: 'About' }` on pages and layouts; a layout's `title: { default, template: '%s · Site' }` applies to the pages below it. A `default` below the root goes through the nearest template above it, like a string (`'Docs'` under `'%s · Site'` is `Docs · Site`), never through the one beside it; `{ absolute: 'Docs' }` skips every template.
|
|
61
|
-
- From C#: `.WithMetadata(new PageMetadata { Title = post.Title, Description = ... })` on the loader's result, merged over the files' metadata.
|
|
65
|
+
- From C#: `.WithMetadata(new PageMetadata { Title = post.Title, Description = ... })` on the loader's result, merged over the files' metadata, so the layouts' title templates wrap `Title`; `AbsoluteTitle = ...` is a title they leave alone.
|
|
66
|
+
- `<html lang>` is `NetjesOptions.Lang` (or the locale), and `PageMetadata.Lang = "nl"` from a loader sets it: a layout loader's for the pages below it, a page loader's wins. A client navigation updates it, and a page without one goes back to the app's. It must be a BCP 47 tag's shape, or setting it throws. Do not set `document.documentElement.lang` in an effect.
|
|
62
67
|
- Below a layout that sets a title, use `metadata`, not a `<title>` element (that makes a second title).
|
|
68
|
+
- `export const viewport: Viewport = { themeColor: '#123', viewportFit: 'cover' }` in a layout or page sets the one `<meta name="viewport">` every document has (default `width=device-width, initial-scale=1`), the `theme-color` tags (one per `{ color, media }`) and `color-scheme`. Never render a viewport `<meta>` yourself: that makes a second one.
|
|
69
|
+
- An installable app is `manifest.webmanifest`, an icon and an `apple-icon.png` in `app/`, `viewport` and `metadata.appleWebApp`, and its start page opted in to offline pages with a worker ([installable app](https://github.com/DennisVerhoeven/netjes/blob/main/docs/guides/metadata.md#an-installable-app)).
|
|
70
|
+
- Write metadata URLs relative (`alternates.canonical: '/blog'`, `openGraph.images: '/og.png'`): they resolve against `Netjes:SiteUrl` in configuration (or `metadataBase`), under the base path. `app.MapSitemap()` and `app.MapRobotsTxt()` without a URL use it too.
|
|
63
71
|
- Code the first paint needs, such as a theme set on `<html>`, goes in `<Script id="theme" strategy="beforeInteractive">{code}</Script>` first in the root layout (a script takes no focus, so the skip link after it stays first): the server writes inline code where it stands and the parser runs it there. An external `beforeInteractive` script runs once the shell is parsed, in order, before the page's code; hydration waits for it, and inline code runs before it. That holds in a server-rendered document: a component that mounts in the browser, after a client navigation or when no sidecar was ready, adds its script after mounting, as `afterInteractive` does. Keep them outside Suspense boundaries. Under a hash-based policy, list the hash of the code as the document carries it, which `inlineScriptHashes` from `netjes/testing` gives, and an external script's origin in `script-src`.
|
|
64
72
|
|
|
65
73
|
## Protecting sections
|
|
66
74
|
|
|
67
|
-
`app.MapLayoutLoader("/dashboard", ...).RequireAuthorization()` protects every page below `app/dashboard/`; `app.MapPages().RequireAuthorization()` protects every page that has no loader of its own; a page loader takes `.RequireAuthorization()` itself. With cookie authentication, answer 401/403 instead of redirecting (`OnRedirectToLogin`, `OnRedirectToAccessDenied`) so `unauthorized.tsx` and `forbidden.tsx` render. `MapPages()`'s conventions never challenge an unknown URL, which stays a 404; a fallback policy covers the not-found fallback too, and challenges a visitor it refuses there. The not-found page, like the status and error pages of server actions and minimal APIs and a page's 401, 403 and pre-authorization status pages (a rate limiter's 429), runs a layout loader only for a visitor the pages in its folder would let in (its conventions and those above it, which pages with a loader carry too, and for file pages `MapPages()`'s or the fallback policy), and renders inside the layouts above it for the rest. So under `MapPages().RequireAuthorization()` the root `unauthorized.tsx` renders without the root layout when that has a loader: make it stand on its own, and never put `.AllowAnonymous()` on a layout loader to keep it, since that opens every page below. `Page.Render(pattern)` from a minimal API runs the page's layout loaders under that endpoint's authorization: protect it as the page is.
|
|
75
|
+
`app.MapLayoutLoader("/dashboard", ...).RequireAuthorization()` protects every page below `app/dashboard/`; `app.MapPages().RequireAuthorization()` protects every page that has no loader of its own; a page loader takes `.RequireAuthorization()` itself. With cookie authentication, answer 401/403 instead of redirecting (`OnRedirectToLogin`, `OnRedirectToAccessDenied`) so `unauthorized.tsx` and `forbidden.tsx` render, or send the visitor to a sign-in page with `cookie.Events.OnRedirectToLogin = context => Page.RedirectToSignIn(context.HttpContext, "/sign-in")`: a document gets a redirect and a client navigation a redirect payload, to `/sign-in?returnUrl=<path and query>`, and a server action's call keeps an empty 401; the sign-in page checks `returnUrl` with `Page.IsLocalUrl` before `Page.LocalRedirect`. `MapPages()`'s conventions never challenge an unknown URL, which stays a 404; a fallback policy covers the not-found fallback too, and challenges a visitor it refuses there. The not-found page, like the status and error pages of server actions and minimal APIs and a page's 401, 403 and pre-authorization status pages (a rate limiter's 429), runs a layout loader only for a visitor the pages in its folder would let in (its conventions and those above it, which pages with a loader carry too, and for file pages `MapPages()`'s or the fallback policy), and renders inside the layouts above it for the rest. So under `MapPages().RequireAuthorization()` the root `unauthorized.tsx` renders without the root layout when that has a loader: make it stand on its own, and never put `.AllowAnonymous()` on a layout loader to keep it, since that opens every page below. `Page.Render(pattern)` from a minimal API runs the page's layout loaders under that endpoint's authorization: protect it as the page is.
|
|
68
76
|
|
|
69
77
|
A check that depends on data (is this user a member of this project?) goes in the page loader as well as in the layout loader: a page's loader runs before its layouts' loaders, and a layout loader is skipped on client navigations within its section while its own route values, the user and the roles stay the same. A layout loader also binds only the route values of its own URL, so it cannot check a deeper one.
|
|
70
78
|
|
|
@@ -75,13 +83,13 @@ A page package is an npm package and a NuGet package of one version that bring p
|
|
|
75
83
|
- The prefix is in folder syntax: `/help`, `/(marketing)/help` (the same URL, inside `app/(marketing)/layout.tsx`), `/[tenant]/help` (`tenant` is a route value). The package's folder of pages merges into `app/` under it, folder by folder: its `layout.tsx` at the mount wraps the app's own pages in `app/help/`, and its `(center)` group wraps an app page in `app/help/(center)/`. Link to its pages with the app's `route('/help/articles/[slug]', { slug })`.
|
|
76
84
|
- An app page of the same shape as a package's page stops the app. To replace the package's page, put the app's in the same folder and add `.Override("/help/contact")` to the mount: it renders with the package's loader, so it reads `pages['/contact']` from the package's generated file (`import { pages } from '@acme/help-center/generated'`), and the app maps no loader for it. Layouts and boundaries cannot be replaced.
|
|
77
85
|
- Conventions on the mount (`.RequireAuthorization()`, `.ExcludeFromExport()`, `.ExcludeFromSitemap()`) cover the package's pages and endpoints, not the app's pages under the prefix; protect those with a layout loader above them, as before. An app layout loader above the mount protects the package's pages too.
|
|
78
|
-
- An unknown URL below the mount renders the package's `not-found.tsx`, after the layout loaders on the way, and `MapPages()`'s authorization, have authorized the visitor.
|
|
86
|
+
- An unknown URL below the mount renders the package's `not-found.tsx`, after the layout loaders on the way, and `MapPages()`'s authorization, have authorized the visitor; those loaders run for the user a page there would have (a package's own sign-in scheme included). Under a fallback policy, an unknown URL is challenged before that, unless the mount gives its not-found conventions of its own: `.ConfigureNotFound(notFound => notFound.AllowAnonymous())` answers the URLs below the mount with the package's 404.
|
|
79
87
|
- A package that draws its own shell (a back-office package) should not render inside the site's header: keep `app/layout.tsx` to providers and the skip link, and move the site's header and footer into `app/(site)/layout.tsx` with the site's pages. URLs do not change. The `package-shell` route warning names an app that has not.
|
|
80
88
|
- Route warnings for packages: `package-shell`, `package-unmounted` (in the build but not mounted), `package-nonce` (a package whose pages stream, under a Content-Security-Policy without a nonce), and `overlap` for a literal page of one source next to a parameter page of the other (`/help/settings` from the package next to the app's `app/help/[section]`).
|
|
81
89
|
|
|
82
90
|
## Base path and locales
|
|
83
91
|
|
|
84
|
-
`app.UsePathBase("/docs")` with `netjes({ basePath: '/docs' })`; links, forms and redirects add it, and app code is written as if at the root (`useHref(path)` for a plain `<a>`). Locale routing is a `[lang]` folder with `AddNetjesLocalization`, `UseNetjesLocalization` and `MapLocaleRedirect`; `useLocale()` reads it.
|
|
92
|
+
`app.UsePathBase("/docs")` with `netjes({ basePath: '/docs' })`; links, forms and redirects add it, and app code is written as if at the root (`useHref(path)` for a plain `<a>`). Locale routing is a `[lang]` folder with `AddNetjesLocalization`, `UseNetjesLocalization` and `MapLocaleRedirect`; `useLocale()` reads it. `MapLocaleRedirect` sends `/` and any URL without a locale that a localized page answers (`/about`) to the visitor's locale with a 307: the cookie `LocaleCookie` names, then `Accept-Language`, then the default. `PrefixDefaultLocale = false` serves the default locale at URLs without it (`/about` in English, `/nl/about` in Dutch) through the page's own loader, actions and authorization, and redirects `/en/about` permanently to `/about`; write default-locale links without the locale. Localized pages get `hreflang` alternates (`Alternates = false` turns them off; an explicit `alternates.languages` wins), and `useAlternateLocales()` gives a language switcher their paths.
|
|
85
93
|
|
|
86
94
|
## More
|
|
87
95
|
|
|
@@ -4,7 +4,7 @@ Test first: write the test, watch it fail for the reason you expect, then change
|
|
|
4
4
|
|
|
5
5
|
## Components and pages: Vitest
|
|
6
6
|
|
|
7
|
-
`netjes()` in `vite.config.ts` sets up Vitest: jsdom, Testing Library cleanup (a config with `setupFiles` of its own lists `netjes/testing/setup` in them), `e2e/`, `dist/`, `bin/` and `obj/` excluded, and in every app a setup file of Netjes's own, which lets Testing Library work with fake timers and hands `createTestApp` the app's query defaults. Inline `test.projects` that share the root's Vite server, Vitest 5's default, get none of this: set `sharedViteServer: false` in the root's `test` options. Tests sit next to the code as `*.test.tsx` and run with `npm test`.
|
|
7
|
+
`netjes()` in `vite.config.ts` sets up Vitest: jsdom, Testing Library cleanup (a config with `setupFiles` of its own lists `netjes/testing/setup` in them), `e2e/`, `dist/`, `bin/` and `obj/` excluded, and in every app a setup file of Netjes's own (`netjes/testing/vitest`; a page package's tests, which run without the plugin, list it in `setupFiles`), which lets Testing Library work with fake timers and hands `createTestApp` the app's query defaults. Inline `test.projects` that share the root's Vite server, Vitest 5's default, get none of this: set `sharedViteServer: false` in the root's `test` options. Tests sit next to the code as `*.test.tsx` and run with `npm test`.
|
|
8
8
|
|
|
9
9
|
```tsx
|
|
10
10
|
import { render, screen } from '@testing-library/react';
|
|
@@ -25,12 +25,15 @@ it('shows the validation error from C# next to the field', async () => {
|
|
|
25
25
|
});
|
|
26
26
|
```
|
|
27
27
|
|
|
28
|
-
`createTestApp({ url, params, shared, queries, defaultOptions, navigation, antiforgery, actions })` returns `{ Wrapper, navigations, queryClient }`:
|
|
28
|
+
`createTestApp({ url, params, shared, queries, defaultOptions, navigation, antiforgery, pageActionState, historyState, actions })` returns `{ Wrapper, navigations, queryClient }`:
|
|
29
29
|
|
|
30
30
|
- `url` and `params` set what `usePathname`, `useSearchParams` and `useParams` see; `shared` is what `useSharedProps` returns; `queries: [{ key, data }]` seeds TanStack Query as a loader's `.WithQuery` would.
|
|
31
31
|
- The `QueryClient` starts from the app's `netjes({ query: { defaultOptions } })`: a failed query or mutation is tried as often as in the app, with no wait between the tries, so the test sees the error the app shows after its last try. `defaultOptions` goes over them: `{ queries: { retry: false } }` shows the error after the first request. Seeded data is fresh for the app's `staleTime` from when `createTestApp()` is called: with a `staleTime` of 0, or in a component rendered after a fake clock moved past it, a seeded query is fetched again as it mounts; answer that request (MSW) or pass `{ queries: { staleTime: 60_000 } }`.
|
|
32
32
|
- `actions` answers server action calls by name: `{ ok: true, result }` or `{ ok: false, status: 422, errors }` (add `fields: ['email']` to name the fields a failed state's `values` keep, as the server does). A failure other than a 422 throws a `ServerActionError`, withheld unless the answer has the `message` the server would send: `{ ok: false, status: 403, errors: {}, message: 'Forbidden' }`. A component that calls an action, even from an effect as it mounts, must render inside `app.Wrapper`: outside it the call fails with "called before the page was ready".
|
|
33
|
-
- `
|
|
33
|
+
- `pageActionState: { errors, values }` is what `usePageActionState()` returns after a page action's input failed its checks, with status 422 (or `status: 429` for a post the rate limiter refused), for the page `route` names (else the URL's path).
|
|
34
|
+
- `historyState: { name: value }` is what `useHistoryState` reads for the entry on screen, as a navigation carried it or an earlier visit left it (a record page's `{ list: '/orders?status=open' }`). A value a component sets is kept; a push or a replace keeps the values of the same path, starts another path over and sets what it carried on top, as the router does.
|
|
35
|
+
- A component with `useNavigationGuard` that holds is asked about a push or a replace (a link, a GET form) first, and `navigations` records it once the guard proceeds; `back` and `forward` are recorded without asking.
|
|
36
|
+
- `navigations` records what happened: `{ type: 'push' | 'replace', href }`, with `historyState` when the navigation carried any (`{ type: 'push', href: '/orders/7', historyState: { list: '/orders' } }`), `{ type: 'refresh' | 'back' | 'forward' }`, `{ type: 'submit', action, data }` for form posts, `{ type: 'action', name, input }` for action calls.
|
|
34
37
|
|
|
35
38
|
Render a page component directly with the props its loader would send: `render(<Post title="Hello" body="..." />, { wrapper: createTestApp({ url: '/blog/hello' }).Wrapper })`. A page made with `definePage` parses them with its schema, so props the loader could not send fail the test with `Invalid props: ...`.
|
|
36
39
|
|
package/src/actions.tsx
CHANGED
|
@@ -213,7 +213,7 @@ export function useAction<TInput, TResult>(
|
|
|
213
213
|
const { actionState } = usePagePayload();
|
|
214
214
|
const initial: ActionState<TResult> | null =
|
|
215
215
|
actionState?.action === action.actionName
|
|
216
|
-
? { ok: false, status: 422, errors: actionState.errors, values: actionState.values }
|
|
216
|
+
? { ok: false, status: actionState.status ?? 422, errors: actionState.errors, values: actionState.values }
|
|
217
217
|
: (options.initialState ?? null);
|
|
218
218
|
const { onSubmit } = options;
|
|
219
219
|
const [state, dispatch, pending] = useActionState((_previous: ActionState<TResult> | null, formData: FormData) => {
|
|
@@ -232,15 +232,16 @@ export type PageActionFailure = { ok: false; status: number; errors: Record<stri
|
|
|
232
232
|
/**
|
|
233
233
|
* After the input of the page's action (`MapPageAction`) failed its checks, its DataAnnotations or
|
|
234
234
|
* `IValidatableObject`: the errors per field and the submitted values of the fields the action declares, as the page
|
|
235
|
-
* is rendered again from its loader, with and without JavaScript
|
|
236
|
-
*
|
|
235
|
+
* is rendered again from its loader, with and without JavaScript, with status 422. After the rate limiter refused the
|
|
236
|
+
* post (`Page.TooManyRequests` in C#), the same with status 429 and the limiter's message under `''`. Else null, also
|
|
237
|
+
* after a server action's failure, which `useAction` reads.
|
|
237
238
|
*/
|
|
238
239
|
export function usePageActionState(): PageActionFailure | null {
|
|
239
240
|
const { actionState, route } = usePagePayload();
|
|
240
241
|
return useMemo(
|
|
241
242
|
() =>
|
|
242
243
|
actionState && route !== null && actionState.action === route
|
|
243
|
-
? { ok: false, status: 422, errors: actionState.errors, values: actionState.values }
|
|
244
|
+
? { ok: false, status: actionState.status ?? 422, errors: actionState.errors, values: actionState.values }
|
|
244
245
|
: null,
|
|
245
246
|
[actionState, route],
|
|
246
247
|
);
|
package/src/client-entry.tsx
CHANGED
|
@@ -86,7 +86,10 @@ globals.__netjes_d = settle;
|
|
|
86
86
|
|
|
87
87
|
const parsed = revivePayload(parseInitialPayload(JSON.parse(dataJson)), deferred.source);
|
|
88
88
|
// Judge the server's seeded data as fresh as the server did when it rendered, so hydration matches.
|
|
89
|
-
|
|
89
|
+
// A document served from offline storage keeps its original query timestamps, as a stored payload does.
|
|
90
|
+
const navigation = performance.getEntriesByType?.('navigation')[0] as PerformanceNavigationTiming | undefined;
|
|
91
|
+
const stored = navigation?.serverTiming?.some(({ name }) => name === 'netjes-stored');
|
|
92
|
+
const payload = stored ? parsed : withClockOffset(parsed, parsed.renderedAt);
|
|
90
93
|
const loader = createModuleLoader(pages, { nameFailedImports: true });
|
|
91
94
|
|
|
92
95
|
/** How long the first page waits before it tries a module that failed to load once more. */
|
package/src/document.tsx
CHANGED
|
@@ -2,7 +2,13 @@ import type { ReactNode } from 'react';
|
|
|
2
2
|
import { DEFERRED_BOOTSTRAP } from './deferred.ts';
|
|
3
3
|
import { DATA_ELEMENT_ID, type DocumentInfo, SHELL_END_ID } from './payload.ts';
|
|
4
4
|
|
|
5
|
-
type DocumentProps = {
|
|
5
|
+
type DocumentProps = {
|
|
6
|
+
info: DocumentInfo;
|
|
7
|
+
/** The `lang` of `<html>`: the first page's (`documentLang`), or else the document's own. */
|
|
8
|
+
lang?: string | undefined;
|
|
9
|
+
dataJson: string;
|
|
10
|
+
children: ReactNode;
|
|
11
|
+
};
|
|
6
12
|
|
|
7
13
|
/**
|
|
8
14
|
* The `<html>` shell around every page. React renders and hydrates the whole document, so `<title>`, `<meta>`
|
|
@@ -13,7 +19,7 @@ type DocumentProps = { info: DocumentInfo; dataJson: string; children: ReactNode
|
|
|
13
19
|
* the head, the payload first in the body. The empty element at the end of the body is the last thing in the shell,
|
|
14
20
|
* which the client entry waits for before it hydrates: a cached entry can run long before the parser gets there.
|
|
15
21
|
*/
|
|
16
|
-
export function Document({ info, dataJson, children }: DocumentProps) {
|
|
22
|
+
export function Document({ info, lang = info.lang, dataJson, children }: DocumentProps) {
|
|
17
23
|
const { nonce } = info;
|
|
18
24
|
// Netjes owns <html> and <body>: the app's layout renders inside the body, so its markup cannot give either one an
|
|
19
25
|
// attribute. A script that runs before hydration can (a theme, a browser extension, a translator), and in development
|
|
@@ -23,12 +29,18 @@ export function Document({ info, dataJson, children }: DocumentProps) {
|
|
|
23
29
|
// the body, and a mismatch there is neither reported nor repaired. The elements in the body are checked as before,
|
|
24
30
|
// their attributes and their text. React does not write the prop into the markup, and production does not check
|
|
25
31
|
// attributes at all. The check is off for `lang` too: the server and the client read it from the same payload, so it
|
|
26
|
-
// differs only when a script changed it, or when Netjes has a bug.
|
|
32
|
+
// differs only when a script changed it, or when Netjes has a bug. This element keeps the first page's `lang`: after
|
|
33
|
+
// a client navigation the router sets the attribute itself (RouterProvider's `documentLang`).
|
|
27
34
|
return (
|
|
28
|
-
<html lang={
|
|
35
|
+
<html lang={lang} suppressHydrationWarning>
|
|
29
36
|
<head>
|
|
30
37
|
<meta charSet="utf-8" />
|
|
31
|
-
|
|
38
|
+
{/* The app's metadata files at the root of app/, which the server found. The route tree writes the viewport tag
|
|
39
|
+
and the rest of the head: it knows the page's viewport and metadata. */}
|
|
40
|
+
{info.head?.icons.map((icon) => (
|
|
41
|
+
<link key={`${icon.rel}:${icon.href}`} rel={icon.rel} href={icon.href} type={icon.type} sizes={icon.sizes} />
|
|
42
|
+
))}
|
|
43
|
+
{info.head?.manifest && <link rel="manifest" href={info.head.manifest} />}
|
|
32
44
|
{/* Vite reads the nonce from here for the styles it injects. */}
|
|
33
45
|
{nonce && <meta property="csp-nonce" nonce={nonce} />}
|
|
34
46
|
{/* Collects Page.Defer values streamed in before the client script runs. A client render finds it in the
|
package/src/index.ts
CHANGED
|
@@ -25,7 +25,7 @@ export {
|
|
|
25
25
|
} from './href.ts';
|
|
26
26
|
export { Image, type ImageProps } from './image.tsx';
|
|
27
27
|
export { Link, type LinkProps } from './link.tsx';
|
|
28
|
-
export { useLocale } from './locale.ts';
|
|
28
|
+
export { useAlternateLocales, useLocale } from './locale.ts';
|
|
29
29
|
export type { ErrorPageProps, LayoutProps } from './modules.ts';
|
|
30
30
|
export {
|
|
31
31
|
type Mounted,
|
|
@@ -36,16 +36,26 @@ export {
|
|
|
36
36
|
mounted,
|
|
37
37
|
} from './mounted.tsx';
|
|
38
38
|
export { useNonce } from './nonce.tsx';
|
|
39
|
+
export { clearOffline, keepOffline, registerServiceWorker } from './offline.ts';
|
|
39
40
|
export type { PageKind, Params, SeededQuery, SegmentRef } from './payload.ts';
|
|
40
41
|
export { usePublicConfig } from './public-config.tsx';
|
|
41
42
|
export { Script, type ScriptProps, type ScriptStrategy } from './script.tsx';
|
|
42
43
|
export {
|
|
44
|
+
type NavigateOptions,
|
|
45
|
+
type NavigationAttempt,
|
|
46
|
+
type NavigationAttemptType,
|
|
47
|
+
type NavigationError,
|
|
48
|
+
type NavigationGuardOptions,
|
|
43
49
|
type NavigationState,
|
|
50
|
+
type SetHistoryState,
|
|
44
51
|
type SubmitError,
|
|
45
52
|
type Router,
|
|
46
53
|
useBasePath,
|
|
54
|
+
useHistoryRestore,
|
|
55
|
+
useHistoryState,
|
|
47
56
|
useHref,
|
|
48
57
|
useNavigation,
|
|
58
|
+
useNavigationGuard,
|
|
49
59
|
useParams,
|
|
50
60
|
usePathname,
|
|
51
61
|
useRouter,
|
|
@@ -55,4 +65,4 @@ export {
|
|
|
55
65
|
useSharedProps,
|
|
56
66
|
} from './router.tsx';
|
|
57
67
|
export type { StandardSchemaV1 } from './schema.ts';
|
|
58
|
-
export type { Metadata, MetadataImage, MetadataTitle } from './metadata.tsx';
|
|
68
|
+
export type { Metadata, MetadataImage, MetadataTitle, ThemeColorDescriptor, Viewport } from './metadata.tsx';
|
package/src/lang.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// The `lang` of `<html>`: a page loader's or a layout loader's `PageMetadata.Lang`, else the root's.
|
|
2
|
+
import type { PagePayload } from './payload.ts';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The shape of a BCP 47 language tag (RFC 5646), as `PageMetadata.Lang` checks it in C#: a primary subtag of two to
|
|
6
|
+
* eight letters, or `x` (private use) or `i` (grandfathered) with at least one subtag after it, then subtags of one to
|
|
7
|
+
* eight letters and digits, each after one hyphen. ASCII only, so no quote, angle bracket or space reaches `<html>`.
|
|
8
|
+
*/
|
|
9
|
+
const LANGUAGE_TAG = /^(?:[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*|[xXiI](?:-[A-Za-z0-9]{1,8})+)$/;
|
|
10
|
+
|
|
11
|
+
export function isLanguageTag(value: string): boolean {
|
|
12
|
+
return LANGUAGE_TAG.test(value);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* The document's `lang` for a page: the page loader's, else the innermost layout loader's, else the locale the page
|
|
17
|
+
* was rendered in (`AddNetjesLocalization`), else `root`, the lang the app's root gave the document (the locale it was
|
|
18
|
+
* first rendered in, or `NetjesOptions.Lang`). It is what the server writes for a fresh load of the page's URL
|
|
19
|
+
* (`DocumentLang` in PageRenderer.cs). A reused segment holds the lang its loader gave it when it last ran.
|
|
20
|
+
*/
|
|
21
|
+
export function documentLang(payload: Pick<PagePayload, 'lang' | 'segments' | 'locale'>, root: string): string {
|
|
22
|
+
if (payload.lang !== undefined) return payload.lang;
|
|
23
|
+
for (let i = payload.segments.length - 1; i >= 0; i--) {
|
|
24
|
+
const lang = payload.segments[i]?.lang;
|
|
25
|
+
if (lang !== undefined) return lang;
|
|
26
|
+
}
|
|
27
|
+
return payload.locale ?? root;
|
|
28
|
+
}
|
package/src/link.tsx
CHANGED
|
@@ -16,6 +16,17 @@ export type LinkProps = Omit<ComponentPropsWithRef<'a'>, 'href'> & {
|
|
|
16
16
|
prefetch?: 'intent' | 'none';
|
|
17
17
|
/** Let the browser follow it with a full page load: for a page of the app that must load in full, or a page on another site. */
|
|
18
18
|
reloadDocument?: boolean;
|
|
19
|
+
/**
|
|
20
|
+
* Mark the link `aria-current="page"` only when its query is the page's whole query: the same parameters with the
|
|
21
|
+
* same values, in any order. Default false: parameters the link leaves out do not count. For a list's paging and sort
|
|
22
|
+
* links, where a link that drops `page` goes to another page of the list.
|
|
23
|
+
*/
|
|
24
|
+
exactQuery?: boolean;
|
|
25
|
+
/**
|
|
26
|
+
* `useHistoryState` values, by name, that the entry the link opens starts with: what a list tells the record it opens.
|
|
27
|
+
* A link the browser follows itself carries none.
|
|
28
|
+
*/
|
|
29
|
+
historyState?: Readonly<Record<string, unknown>>;
|
|
19
30
|
};
|
|
20
31
|
|
|
21
32
|
const BASE = 'http://netjes.invalid';
|
|
@@ -34,17 +45,19 @@ function sameValues(a: string[], b: string[]) {
|
|
|
34
45
|
/**
|
|
35
46
|
* Whether the link goes to the page on screen. An href with a `#` points to a place in a page, so it never does.
|
|
36
47
|
* Otherwise its URL under the base path has the page's path, give or take one trailing slash, and the page's
|
|
37
|
-
* values for each query parameter it names; parameters it leaves out do not count
|
|
38
|
-
* enter, against a fixed origin, so the server and the browser agree.
|
|
48
|
+
* values for each query parameter it names; parameters it leaves out do not count, unless `exactQuery` asks for the
|
|
49
|
+
* page's parameters too. Only the path and the query enter, against a fixed origin, so the server and the browser agree.
|
|
39
50
|
*/
|
|
40
|
-
function isCurrentPage(href: string, pathname: string, search: URLSearchParams, basePath: string) {
|
|
51
|
+
function isCurrentPage(href: string, pathname: string, search: URLSearchParams, basePath: string, exactQuery: boolean) {
|
|
41
52
|
if (href.includes('#')) return false;
|
|
42
53
|
const query = search.toString();
|
|
43
54
|
// The page's URL as the browser has it: the base path, then the page's path, even one that starts like the base path.
|
|
44
55
|
const page = new URL(BASE + basePath + pathname + (query ? `?${query}` : ''));
|
|
45
56
|
const target = new URL(withBasePath(href, basePath), page);
|
|
46
57
|
if (target.origin !== BASE || withoutTrailingSlash(target.pathname) !== withoutTrailingSlash(page.pathname)) return false;
|
|
47
|
-
|
|
58
|
+
const keys = new Set(target.searchParams.keys());
|
|
59
|
+
if (exactQuery) for (const key of search.keys()) keys.add(key);
|
|
60
|
+
return [...keys].every((key) => sameValues(target.searchParams.getAll(key), search.getAll(key)));
|
|
48
61
|
}
|
|
49
62
|
|
|
50
63
|
function isPlainLeftClick(event: MouseEvent<HTMLAnchorElement>) {
|
|
@@ -63,10 +76,24 @@ function isPlainLeftClick(event: MouseEvent<HTMLAnchorElement>) {
|
|
|
63
76
|
/**
|
|
64
77
|
* An `<a>` that navigates on the client. Ctrl/cmd-click, new tabs and external URLs behave like a normal link. It sets
|
|
65
78
|
* `aria-current="page"` on a link to the page on screen: the same path, one trailing slash aside, and the page's values
|
|
66
|
-
* for each query parameter the link names
|
|
67
|
-
*
|
|
79
|
+
* for each query parameter the link names (with `exactQuery`, for every parameter the page has too). A link with a `#`
|
|
80
|
+
* is never marked, and an `aria-current` prop wins. After a navigation to another page, the router announces the page
|
|
81
|
+
* and starts the focus over at the top of the document.
|
|
68
82
|
*/
|
|
69
|
-
export function Link({
|
|
83
|
+
export function Link({
|
|
84
|
+
href,
|
|
85
|
+
replace = false,
|
|
86
|
+
scroll = true,
|
|
87
|
+
prefetch = 'intent',
|
|
88
|
+
reloadDocument = false,
|
|
89
|
+
exactQuery = false,
|
|
90
|
+
historyState,
|
|
91
|
+
onClick,
|
|
92
|
+
onMouseEnter,
|
|
93
|
+
onFocus,
|
|
94
|
+
onTouchStart,
|
|
95
|
+
...rest
|
|
96
|
+
}: LinkProps) {
|
|
70
97
|
const router = useInternalRouter();
|
|
71
98
|
const pathname = usePathname();
|
|
72
99
|
const search = useSearchParams();
|
|
@@ -78,7 +105,7 @@ export function Link({ href, replace = false, scroll = true, prefetch = 'intent'
|
|
|
78
105
|
return (
|
|
79
106
|
<a
|
|
80
107
|
href={withBasePath(href, basePath)}
|
|
81
|
-
aria-current={isCurrentPage(href, pathname, search, basePath) ? 'page' : undefined}
|
|
108
|
+
aria-current={isCurrentPage(href, pathname, search, basePath, exactQuery) ? 'page' : undefined}
|
|
82
109
|
{...rest}
|
|
83
110
|
onClick={(event) => {
|
|
84
111
|
// Read before the app's own onClick, which runs as the link is followed: where it moves the focus, such as
|
|
@@ -88,7 +115,8 @@ export function Link({ href, replace = false, scroll = true, prefetch = 'intent'
|
|
|
88
115
|
if (event.defaultPrevented || reloadDocument || !isPlainLeftClick(event)) return;
|
|
89
116
|
if (new URL(href, window.location.href).origin !== window.location.origin) return;
|
|
90
117
|
event.preventDefault();
|
|
91
|
-
|
|
118
|
+
const options = { scroll, focusedAtStart, ...(historyState ? { historyState } : {}) };
|
|
119
|
+
void (replace ? router.replace(href, options) : router.push(href, options));
|
|
92
120
|
}}
|
|
93
121
|
onMouseEnter={(event) => {
|
|
94
122
|
onMouseEnter?.(event);
|
package/src/locale.ts
CHANGED
|
@@ -4,3 +4,8 @@ import { usePagePayload } from './router.tsx';
|
|
|
4
4
|
export function useLocale(): string | null {
|
|
5
5
|
return usePagePayload().locale ?? null;
|
|
6
6
|
}
|
|
7
|
+
|
|
8
|
+
/** The current page's alternate locale URLs as app-root-relative paths, including x-default when present. */
|
|
9
|
+
export function useAlternateLocales(): { locale: string; href: string }[] {
|
|
10
|
+
return Object.entries(usePagePayload().localeAlternates ?? {}).map(([locale, href]) => ({ locale, href }));
|
|
11
|
+
}
|