netjes 0.0.2 → 0.0.4
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 +13 -11
- package/cli/agents.mjs +25 -2
- package/cli/commands.mjs +56 -6
- package/cli/help.mjs +7 -2
- package/cli/info.mjs +275 -33
- package/cli/routes.mjs +35 -8
- package/cli/scaffold.mjs +31 -4
- package/dist/actions.d.ts +7 -2
- package/dist/actions.d.ts.map +1 -1
- package/dist/actions.js +9 -3
- package/dist/actions.js.map +1 -1
- package/dist/client-entry.d.ts +1 -0
- package/dist/client-entry.d.ts.map +1 -1
- package/dist/client-entry.js +19 -2
- package/dist/client-entry.js.map +1 -1
- package/dist/deferred.d.ts +11 -0
- package/dist/deferred.d.ts.map +1 -1
- package/dist/deferred.js +15 -1
- package/dist/deferred.js.map +1 -1
- package/dist/document.d.ts.map +1 -1
- package/dist/document.js +10 -1
- package/dist/document.js.map +1 -1
- package/dist/errors.d.ts +7 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +11 -0
- package/dist/errors.js.map +1 -0
- package/dist/form.d.ts +5 -5
- package/dist/form.d.ts.map +1 -1
- package/dist/form.js +5 -2
- package/dist/form.js.map +1 -1
- package/dist/href.d.ts +31 -3
- package/dist/href.d.ts.map +1 -1
- package/dist/href.js +131 -10
- package/dist/href.js.map +1 -1
- package/dist/image.d.ts +3 -3
- package/dist/image.d.ts.map +1 -1
- package/dist/image.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/link.d.ts +15 -7
- package/dist/link.d.ts.map +1 -1
- package/dist/link.js +38 -7
- package/dist/link.js.map +1 -1
- package/dist/metadata.d.ts +8 -2
- package/dist/metadata.d.ts.map +1 -1
- package/dist/metadata.js +14 -5
- package/dist/metadata.js.map +1 -1
- package/dist/modules.d.ts +15 -1
- package/dist/modules.d.ts.map +1 -1
- package/dist/modules.js.map +1 -1
- package/dist/mounted.d.ts +55 -0
- package/dist/mounted.d.ts.map +1 -0
- package/dist/mounted.js +110 -0
- package/dist/mounted.js.map +1 -0
- package/dist/navigation-focus.d.ts +38 -0
- package/dist/navigation-focus.d.ts.map +1 -0
- package/dist/navigation-focus.js +71 -0
- package/dist/navigation-focus.js.map +1 -0
- package/dist/payload.d.ts +8 -0
- package/dist/payload.d.ts.map +1 -1
- package/dist/payload.js +28 -0
- package/dist/payload.js.map +1 -1
- package/dist/query.d.ts +5 -2
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +11 -8
- package/dist/query.js.map +1 -1
- package/dist/render-document.d.ts +74 -0
- package/dist/render-document.d.ts.map +1 -0
- package/dist/render-document.js +393 -0
- package/dist/render-document.js.map +1 -0
- package/dist/route-announcer.d.ts +18 -0
- package/dist/route-announcer.d.ts.map +1 -0
- package/dist/route-announcer.js +58 -0
- package/dist/route-announcer.js.map +1 -0
- package/dist/route-tree.d.ts +6 -2
- package/dist/route-tree.d.ts.map +1 -1
- package/dist/route-tree.js +17 -7
- package/dist/route-tree.js.map +1 -1
- package/dist/router.d.ts +28 -5
- package/dist/router.d.ts.map +1 -1
- package/dist/router.js +71 -26
- package/dist/router.js.map +1 -1
- package/dist/script.d.ts +28 -5
- package/dist/script.d.ts.map +1 -1
- package/dist/script.js +192 -21
- package/dist/script.js.map +1 -1
- package/dist/server-render.d.ts.map +1 -1
- package/dist/server-render.js +4 -1
- package/dist/server-render.js.map +1 -1
- package/dist/testing-vitest.d.ts +8 -0
- package/dist/testing-vitest.d.ts.map +1 -0
- package/dist/testing-vitest.js +26 -0
- package/dist/testing-vitest.js.map +1 -0
- package/dist/testing.d.ts +17 -1
- package/dist/testing.d.ts.map +1 -1
- package/dist/testing.js +18 -3
- package/dist/testing.js.map +1 -1
- package/dist/zod-jitless.d.ts +2 -0
- package/dist/zod-jitless.d.ts.map +1 -0
- package/dist/zod-jitless.js +4 -0
- package/dist/zod-jitless.js.map +1 -0
- package/package.json +1 -1
- package/sidecar/server.mjs +109 -15
- package/skills/netjes/SKILL.md +15 -7
- package/skills/netjes/references/caching-and-streaming.md +37 -4
- package/skills/netjes/references/data-and-actions.md +15 -7
- package/skills/netjes/references/deployment.md +7 -3
- package/skills/netjes/references/routing.md +32 -9
- package/skills/netjes/references/testing.md +23 -7
- package/src/actions.tsx +9 -3
- package/src/client-entry.tsx +20 -2
- package/src/deferred.ts +14 -1
- package/src/document.tsx +22 -3
- package/src/errors.ts +12 -0
- package/src/form.tsx +10 -7
- package/src/href.ts +137 -11
- package/src/image.tsx +3 -3
- package/src/index.ts +19 -1
- package/src/link.tsx +47 -13
- package/src/metadata.tsx +19 -6
- package/src/modules.ts +15 -2
- package/src/mounted.tsx +160 -0
- package/src/navigation-focus.ts +75 -0
- package/src/payload.ts +32 -0
- package/src/query.tsx +14 -8
- package/src/render-document.tsx +483 -0
- package/src/route-announcer.tsx +69 -0
- package/src/route-tree.tsx +17 -6
- package/src/router.tsx +116 -31
- package/src/script.tsx +214 -23
- package/src/server-render.tsx +4 -1
- package/src/testing-vitest.ts +37 -0
- package/src/testing.tsx +38 -5
- package/src/virtual.d.ts +8 -1
- package/src/zod-jitless.ts +15 -0
- package/template/.dockerignore +3 -0
- package/template/Dockerfile +11 -1
- package/template/README.md +11 -7
- package/template/_AGENTS.md +38 -9
- package/template/__NAME__.csproj +2 -0
- package/template/app/document.test.ts +29 -0
- package/template/app/error.tsx +3 -2
- package/template/app/layout.tsx +10 -1
- package/template/docker-compose.override.yml +4 -3
- package/template/docker-compose.prod.yml +2 -1
- package/template/e2e/home.spec.ts +32 -0
- package/template/generated/netjes.ts +43 -14
- package/template/package.json +4 -1
- package/template/playwright.config.ts +36 -0
- package/template/tests/__NAME__.Tests/AppFactory.cs +31 -0
- package/template/tests/__NAME__.Tests/HomePageTests.cs +55 -0
- package/template/tests/__NAME__.Tests/__NAME__.Tests.csproj +30 -0
- package/template/tsconfig.app.json +20 -0
- package/template/tsconfig.json +2 -17
- package/template/tsconfig.node.json +8 -0
- package/vite/packages.mjs +345 -0
- package/vite/plugin.d.ts +16 -1
- package/vite/plugin.mjs +224 -34
package/src/href.ts
CHANGED
|
@@ -25,25 +25,65 @@ function matches(pattern: readonly string[], path: readonly string[]): boolean {
|
|
|
25
25
|
}
|
|
26
26
|
|
|
27
27
|
/**
|
|
28
|
-
* Whether a URL
|
|
29
|
-
*
|
|
28
|
+
* Whether a URL has the shape of a link, as a C# `Href` checks it: root-relative (`/…`, but not `//…` or `/\…`, which
|
|
29
|
+
* browsers read as another host), a link within the page (`?…`, `#…`), or an `http:`, `https:`, `mailto:` or `tel:`
|
|
30
|
+
* URL, with no ASCII control character and no space at either end. It does not ask which page a path names: a page
|
|
31
|
+
* package's generated file, which cannot know the app's pages, checks its `Href` with this.
|
|
30
32
|
*/
|
|
31
|
-
export function
|
|
33
|
+
export function isHrefShape(value: string): boolean {
|
|
34
|
+
// Browsers drop tabs and newlines anywhere in a URL, and control characters and spaces at either end: `/\t/host`
|
|
35
|
+
// would be `//host`. A C# Href refuses the same.
|
|
36
|
+
if (/[\u0000-\u001F\u007F]/.test(value) || value.startsWith(' ') || value.endsWith(' ')) return false;
|
|
32
37
|
if (/^(https?:|mailto:|tel:)/i.test(value) || value.startsWith('?') || value.startsWith('#')) return true;
|
|
33
38
|
// "//host" and "/\host" are other hosts as far as browsers are concerned.
|
|
34
|
-
|
|
39
|
+
return value.startsWith('/') && !value.startsWith('//') && !value.startsWith('/\\');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Whether a URL is one of the app's pages (by route pattern), a link within the page (`?…`, `#…`), or another
|
|
44
|
+
* site. The generated `isHref()` and `Href` schema call this to check URLs that come from data. A URL with an ASCII
|
|
45
|
+
* control character, or with a space at either end, is none of these.
|
|
46
|
+
*/
|
|
47
|
+
export function isRouteHref(value: string, patterns: readonly string[]): boolean {
|
|
48
|
+
if (!isHrefShape(value)) return false;
|
|
49
|
+
if (!value.startsWith('/')) return true;
|
|
35
50
|
const path = (value.split(/[?#]/, 1)[0] ?? '').split('/').filter(Boolean);
|
|
36
51
|
return patterns.some((pattern) => matches(pattern.split('/').filter(Boolean), path));
|
|
37
52
|
}
|
|
38
53
|
|
|
54
|
+
/**
|
|
55
|
+
* A segment that would change the URL's path when a browser or `fetch` resolves it: `.` and `..` are dot segments,
|
|
56
|
+
* which move up the path, and an empty one doubles a slash, which right after the leading one names another host.
|
|
57
|
+
*/
|
|
58
|
+
function changesThePath(segment: string): boolean {
|
|
59
|
+
return segment === '' || segment === '.' || segment === '..';
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const changesThePathMessage = "a '.', '..' or empty segment would change the URL's path";
|
|
63
|
+
|
|
39
64
|
/**
|
|
40
65
|
* Builds the URL for a route pattern written in file-name syntax (`/blog/[slug]`, `/docs/[...path]`,
|
|
41
|
-
* `/shop/[[...filters]]`), encoding every segment value.
|
|
66
|
+
* `/shop/[[...filters]]`), encoding every segment value. A value, or a catch-all entry, that is `.`, `..` or empty
|
|
67
|
+
* throws, since it would change the path the URL names. `options.hash` adds a fragment after the query: the id of an
|
|
68
|
+
* element in the page, with one leading `#` dropped and the rest encoded; with nothing left, no fragment is added. The
|
|
69
|
+
* generated `route()` helper calls this with typed params.
|
|
42
70
|
*/
|
|
43
|
-
export function buildHref(
|
|
71
|
+
export function buildHref(
|
|
72
|
+
pattern: string,
|
|
73
|
+
params: Record<string, unknown>,
|
|
74
|
+
search?: SearchParamsInput,
|
|
75
|
+
options?: { hash?: string | undefined },
|
|
76
|
+
): string {
|
|
44
77
|
const missing = (name: string): never => {
|
|
45
78
|
throw new Error(`netjes: route '${pattern}' needs the parameter '${name}'`);
|
|
46
79
|
};
|
|
80
|
+
const encode = (name: string, value: unknown): string => {
|
|
81
|
+
const text = String(value);
|
|
82
|
+
if (changesThePath(text)) {
|
|
83
|
+
throw new Error(`netjes: route '${pattern}' cannot take '${text}' for the parameter '${name}': ${changesThePathMessage}`);
|
|
84
|
+
}
|
|
85
|
+
return encodeURIComponent(text);
|
|
86
|
+
};
|
|
47
87
|
const segments = pattern
|
|
48
88
|
.split('/')
|
|
49
89
|
.filter(Boolean)
|
|
@@ -51,29 +91,115 @@ export function buildHref(pattern: string, params: Record<string, unknown>, sear
|
|
|
51
91
|
const optional = /^\[\[\.\.\.(\w+)\]\]$/.exec(segment)?.[1];
|
|
52
92
|
if (optional) {
|
|
53
93
|
const values = params[optional];
|
|
54
|
-
return Array.isArray(values) ? values.map((v) =>
|
|
94
|
+
return Array.isArray(values) ? values.map((v) => encode(optional, v)) : [];
|
|
55
95
|
}
|
|
56
96
|
const catchAll = /^\[\.\.\.(\w+)\]$/.exec(segment)?.[1];
|
|
57
97
|
if (catchAll) {
|
|
58
98
|
const values = params[catchAll];
|
|
59
99
|
if (!Array.isArray(values) || values.length === 0) return missing(catchAll);
|
|
60
|
-
return values.map((v) =>
|
|
100
|
+
return values.map((v) => encode(catchAll, v));
|
|
61
101
|
}
|
|
62
102
|
const single = /^\[(\w+)\]$/.exec(segment)?.[1];
|
|
63
103
|
if (single) {
|
|
64
104
|
const value = params[single];
|
|
65
105
|
if (value === undefined || value === null || value === '') return missing(single);
|
|
66
|
-
return [
|
|
106
|
+
return [encode(single, value)];
|
|
67
107
|
}
|
|
68
108
|
return [segment];
|
|
69
109
|
});
|
|
70
110
|
|
|
71
111
|
const query = new URLSearchParams();
|
|
112
|
+
appendSearch(query, search);
|
|
113
|
+
const queryString = query.toString();
|
|
114
|
+
const fragment = (options?.hash ?? '').replace(/^#/, '');
|
|
115
|
+
return `/${segments.join('/')}${queryString ? `?${queryString}` : ''}${fragment ? `#${encodeURIComponent(fragment)}` : ''}`;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Appends each value of `search`, a list repeating its key; `null` and `undefined` leave the key out. */
|
|
119
|
+
function appendSearch(query: URLSearchParams, search: Readonly<Record<string, unknown>> | undefined): void {
|
|
72
120
|
for (const [key, value] of Object.entries(search ?? {})) {
|
|
73
|
-
for (const item of Array.isArray(value) ? value : [value]) {
|
|
121
|
+
for (const item of Array.isArray(value) ? (value as readonly unknown[]) : [value]) {
|
|
74
122
|
if (item !== undefined && item !== null) query.append(key, String(item));
|
|
75
123
|
}
|
|
76
124
|
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** A missing route value: `undefined`, `null` or `''`. */
|
|
128
|
+
function absent(value: unknown): boolean {
|
|
129
|
+
return value === undefined || value === null || value === '';
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Builds the URL of one of the app's endpoints from its route template, as the generated file writes it: the
|
|
134
|
+
* literals as they are (with `%`, `{`, `}`, `#` and `\` encoded), `{name}`, `{name?}`, `{name=default}` (the default
|
|
135
|
+
* encoded), `{*name}` and `{**name}`, without constraints. Each route value is encoded; a `{**name}` value keeps its
|
|
136
|
+
* slashes, and a `{*name}` value has them encoded. A value that would make a segment `.` or `..`, or a `{**name}` value
|
|
137
|
+
* with such a piece or with an empty one before its end (`/x`, `a//b`), throws `netjes: endpoint '<endpoint>' cannot
|
|
138
|
+
* take '<value>' for the route value '<name>'`, since it would change the path the URL names. A missing, `null` or
|
|
139
|
+
* empty optional value drops its segment, or its
|
|
140
|
+
* part of a segment with the `.` before it (`{name}.{ext?}`); a missing value with a default is filled in, unless it
|
|
141
|
+
* is a whole segment at the end, which is dropped; a missing, `null` or empty required value, or an optional one whose
|
|
142
|
+
* segment is followed by one that stays, throws `netjes: endpoint '<endpoint>' needs the route value '<name>'`. The
|
|
143
|
+
* values the template does not name are the query string, followed by `search`. The result is root-relative and has no base path: pass it through
|
|
144
|
+
* `useHref` for a `fetch` or an `<a href>`. The generated `endpointUrl()` calls this with typed values.
|
|
145
|
+
*/
|
|
146
|
+
export function buildEndpointUrl(
|
|
147
|
+
template: string,
|
|
148
|
+
values: Readonly<Record<string, unknown>>,
|
|
149
|
+
search?: SearchParamsInput,
|
|
150
|
+
endpoint?: string,
|
|
151
|
+
): string {
|
|
152
|
+
const needs = (name: string) => new Error(`netjes: endpoint '${endpoint ?? template}' needs the route value '${name}'`);
|
|
153
|
+
const cannotTake = (name: string, value: unknown) =>
|
|
154
|
+
new Error(`netjes: endpoint '${endpoint ?? template}' cannot take '${String(value)}' for the route value '${name}': ${changesThePathMessage}`);
|
|
155
|
+
const named = new Set<string>();
|
|
156
|
+
// Each segment's text, and the name of the value it is missing, when the segment can go for want of it.
|
|
157
|
+
const segments: { text: string; missing: string | undefined }[] = [];
|
|
158
|
+
for (const segment of template.split('/').filter(Boolean)) {
|
|
159
|
+
let text = '';
|
|
160
|
+
let missing: string | undefined;
|
|
161
|
+
// The value that made the segment's text, which must not leave it a dot segment.
|
|
162
|
+
let filled: string | undefined;
|
|
163
|
+
for (const part of segment.split(/(\{[^}]*\})/).filter(Boolean)) {
|
|
164
|
+
const parameter = /^\{(\*\*?)?([^=?]+?)(\?|=([^]*))?\}$/.exec(part);
|
|
165
|
+
if (!parameter) {
|
|
166
|
+
text += part;
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const [, star, name = '', marker, fallback] = parameter;
|
|
171
|
+
named.add(name);
|
|
172
|
+
const value = values[name];
|
|
173
|
+
if (!absent(value) && star === '**') {
|
|
174
|
+
// Each piece is a segment of its own; an empty last one is a trailing slash.
|
|
175
|
+
const pieces = String(value).split('/');
|
|
176
|
+
if (pieces.some((piece, i) => (piece === '' ? i < pieces.length - 1 : changesThePath(piece)))) throw cannotTake(name, value);
|
|
177
|
+
text += pieces.map((piece) => encodeURIComponent(piece)).join('/');
|
|
178
|
+
} else if (!absent(value)) {
|
|
179
|
+
text += encodeURIComponent(String(value));
|
|
180
|
+
filled = name;
|
|
181
|
+
} else if (fallback !== undefined) {
|
|
182
|
+
text += fallback;
|
|
183
|
+
if (part === segment) missing = name;
|
|
184
|
+
} else if (marker === '?' || star) {
|
|
185
|
+
// An optional value after a literal `.` takes the dot with it.
|
|
186
|
+
if (text.endsWith('.')) text = text.slice(0, -1);
|
|
187
|
+
if (!text) missing = name;
|
|
188
|
+
} else {
|
|
189
|
+
throw needs(name);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
if (filled && changesThePath(text)) throw cannotTake(filled, values[filled]);
|
|
193
|
+
if (text || missing) segments.push({ text, missing });
|
|
194
|
+
}
|
|
195
|
+
while (segments.at(-1)?.missing) segments.pop();
|
|
196
|
+
// A segment left out before one that stays: routing would not match, or would read the next value as this one.
|
|
197
|
+
const leftOut = segments.find((segment) => !segment.text)?.missing;
|
|
198
|
+
if (leftOut) throw needs(leftOut);
|
|
199
|
+
|
|
200
|
+
const query = new URLSearchParams();
|
|
201
|
+
appendSearch(query, Object.fromEntries(Object.entries(values).filter(([key]) => !named.has(key))));
|
|
202
|
+
appendSearch(query, search);
|
|
77
203
|
const queryString = query.toString();
|
|
78
|
-
return `/${segments.join('/')}${queryString ? `?${queryString}` : ''}`;
|
|
204
|
+
return `/${segments.map((s) => s.text).join('/')}${queryString ? `?${queryString}` : ''}`;
|
|
79
205
|
}
|
package/src/image.tsx
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type
|
|
1
|
+
import { type ComponentPropsWithRef, createContext, useContext } from 'react';
|
|
2
2
|
import { preload } from 'react-dom';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -17,8 +17,8 @@ const ImageConfigContext = createContext<ImageConfig>(DEFAULT_CONFIG);
|
|
|
17
17
|
|
|
18
18
|
export const ImageConfigProvider = ImageConfigContext.Provider;
|
|
19
19
|
|
|
20
|
-
/** The props of `<Image>`: an `<img>`'s own, with a required size and `alt`, and the optimizer's options. */
|
|
21
|
-
export type ImageProps = Omit<
|
|
20
|
+
/** The props of `<Image>`: an `<img>`'s own and its ref, with a required size and `alt`, and the optimizer's options. */
|
|
21
|
+
export type ImageProps = Omit<ComponentPropsWithRef<'img'>, 'src' | 'srcSet' | 'width' | 'height' | 'loading' | 'alt'> & {
|
|
22
22
|
/** A path in `public/` (`/img/hero.png`) or a URL on a host in Netjes:Images:RemoteHosts. */
|
|
23
23
|
src: string;
|
|
24
24
|
/** Required, as for any image; `""` for decorative ones. */
|
package/src/index.ts
CHANGED
|
@@ -9,14 +9,32 @@ export {
|
|
|
9
9
|
usePageActionState,
|
|
10
10
|
} from './actions.tsx';
|
|
11
11
|
export { defineLayout, definePage } from './define-page.tsx';
|
|
12
|
+
export { CSP_SCRIPT_HASHES } from './deferred.ts';
|
|
12
13
|
export { useDraftMode } from './draft-mode.ts';
|
|
13
14
|
export { type DynamicOptions, clientOnly, dynamic } from './dynamic.tsx';
|
|
14
15
|
export { Form, type FormAction, type FormProps, SubmitButton, type SubmitButtonProps } from './form.tsx';
|
|
15
|
-
export {
|
|
16
|
+
export {
|
|
17
|
+
type Href,
|
|
18
|
+
type Register,
|
|
19
|
+
type SearchParamsInput,
|
|
20
|
+
type SearchValue,
|
|
21
|
+
buildEndpointUrl,
|
|
22
|
+
buildHref,
|
|
23
|
+
isHrefShape,
|
|
24
|
+
isRouteHref,
|
|
25
|
+
} from './href.ts';
|
|
16
26
|
export { Image, type ImageProps } from './image.tsx';
|
|
17
27
|
export { Link, type LinkProps } from './link.tsx';
|
|
18
28
|
export { useLocale } from './locale.ts';
|
|
19
29
|
export type { ErrorPageProps, LayoutProps } from './modules.ts';
|
|
30
|
+
export {
|
|
31
|
+
type Mounted,
|
|
32
|
+
type MountedFormProps,
|
|
33
|
+
type MountedLinkProps,
|
|
34
|
+
type MountedRouter,
|
|
35
|
+
type MountedSubmitButtonProps,
|
|
36
|
+
mounted,
|
|
37
|
+
} from './mounted.tsx';
|
|
20
38
|
export { useNonce } from './nonce.tsx';
|
|
21
39
|
export type { PageKind, Params, SeededQuery, SegmentRef } from './payload.ts';
|
|
22
40
|
export { usePublicConfig } from './public-config.tsx';
|
package/src/link.tsx
CHANGED
|
@@ -1,25 +1,50 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { ComponentPropsWithRef, MouseEvent } from 'react';
|
|
2
2
|
import type { Href } from './href.ts';
|
|
3
|
-
import { useBasePath, useInternalRouter, usePathname, withBasePath } from './router.tsx';
|
|
3
|
+
import { useBasePath, useInternalRouter, usePathname, useSearchParams, withBasePath } from './router.tsx';
|
|
4
4
|
|
|
5
|
-
/** The props of `<Link>`: an anchor's own, with a typed `href` and the client navigation options. */
|
|
6
|
-
export type LinkProps = Omit<
|
|
5
|
+
/** The props of `<Link>`: an anchor's own and its ref, with a typed `href` and the client navigation options. */
|
|
6
|
+
export type LinkProps = Omit<ComponentPropsWithRef<'a'>, 'href'> & {
|
|
7
7
|
/** Typed by the app's routes once `netjes generate` has registered them. */
|
|
8
8
|
href: Href;
|
|
9
9
|
replace?: boolean;
|
|
10
|
-
/**
|
|
10
|
+
/**
|
|
11
|
+
* Scroll to the top after navigating, or to the #fragment's element, which then takes the focus. Default true. `false`
|
|
12
|
+
* keeps the scroll position, and the focus on the link while the link has it.
|
|
13
|
+
*/
|
|
11
14
|
scroll?: boolean;
|
|
12
|
-
/** `intent` (default) fetches the next page on hover or
|
|
15
|
+
/** `intent` (default) fetches the next page on hover, focus or touch. */
|
|
13
16
|
prefetch?: 'intent' | 'none';
|
|
14
|
-
/** Let the browser follow it with a full page load
|
|
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. */
|
|
15
18
|
reloadDocument?: boolean;
|
|
16
19
|
};
|
|
17
20
|
|
|
18
21
|
const BASE = 'http://netjes.invalid';
|
|
19
22
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
return
|
|
23
|
+
/** One trailing slash makes no other page: `/docs/` is `/docs`, and `/` stays `/`. */
|
|
24
|
+
function withoutTrailingSlash(path: string) {
|
|
25
|
+
return path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The same values, in any order, as often each. */
|
|
29
|
+
function sameValues(a: string[], b: string[]) {
|
|
30
|
+
const sorted = [...b].sort();
|
|
31
|
+
return a.length === b.length && [...a].sort().every((value, i) => value === sorted[i]);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 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
|
+
* 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. Only the path and the query
|
|
38
|
+
* enter, against a fixed origin, so the server and the browser agree.
|
|
39
|
+
*/
|
|
40
|
+
function isCurrentPage(href: string, pathname: string, search: URLSearchParams, basePath: string) {
|
|
41
|
+
if (href.includes('#')) return false;
|
|
42
|
+
const query = search.toString();
|
|
43
|
+
// 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
|
+
const page = new URL(BASE + basePath + pathname + (query ? `?${query}` : ''));
|
|
45
|
+
const target = new URL(withBasePath(href, basePath), page);
|
|
46
|
+
if (target.origin !== BASE || withoutTrailingSlash(target.pathname) !== withoutTrailingSlash(page.pathname)) return false;
|
|
47
|
+
return [...new Set(target.searchParams.keys())].every((key) => sameValues(target.searchParams.getAll(key), search.getAll(key)));
|
|
23
48
|
}
|
|
24
49
|
|
|
25
50
|
function isPlainLeftClick(event: MouseEvent<HTMLAnchorElement>) {
|
|
@@ -35,10 +60,16 @@ function isPlainLeftClick(event: MouseEvent<HTMLAnchorElement>) {
|
|
|
35
60
|
);
|
|
36
61
|
}
|
|
37
62
|
|
|
38
|
-
/**
|
|
63
|
+
/**
|
|
64
|
+
* An `<a>` that navigates on the client. Ctrl/cmd-click, new tabs and external URLs behave like a normal link. It sets
|
|
65
|
+
* `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. A link with a `#` is never marked, and an `aria-current` prop wins. After a
|
|
67
|
+
* navigation to another page, the router announces the page and starts the focus over at the top of the document.
|
|
68
|
+
*/
|
|
39
69
|
export function Link({ href, replace = false, scroll = true, prefetch = 'intent', reloadDocument = false, onClick, onMouseEnter, onFocus, onTouchStart, ...rest }: LinkProps) {
|
|
40
70
|
const router = useInternalRouter();
|
|
41
71
|
const pathname = usePathname();
|
|
72
|
+
const search = useSearchParams();
|
|
42
73
|
const basePath = useBasePath();
|
|
43
74
|
const warm = () => {
|
|
44
75
|
if (prefetch === 'intent' && !reloadDocument) router.prefetch(href);
|
|
@@ -47,14 +78,17 @@ export function Link({ href, replace = false, scroll = true, prefetch = 'intent'
|
|
|
47
78
|
return (
|
|
48
79
|
<a
|
|
49
80
|
href={withBasePath(href, basePath)}
|
|
50
|
-
aria-current={
|
|
81
|
+
aria-current={isCurrentPage(href, pathname, search, basePath) ? 'page' : undefined}
|
|
51
82
|
{...rest}
|
|
52
83
|
onClick={(event) => {
|
|
84
|
+
// Read before the app's own onClick, which runs as the link is followed: where it moves the focus, such as
|
|
85
|
+
// back to the button of a menu that closes, the router leaves it.
|
|
86
|
+
const focusedAtStart = document.activeElement;
|
|
53
87
|
onClick?.(event);
|
|
54
88
|
if (event.defaultPrevented || reloadDocument || !isPlainLeftClick(event)) return;
|
|
55
89
|
if (new URL(href, window.location.href).origin !== window.location.origin) return;
|
|
56
90
|
event.preventDefault();
|
|
57
|
-
void (replace ? router.replace(href, { scroll }) : router.push(href, { scroll }));
|
|
91
|
+
void (replace ? router.replace(href, { scroll, focusedAtStart }) : router.push(href, { scroll, focusedAtStart }));
|
|
58
92
|
}}
|
|
59
93
|
onMouseEnter={(event) => {
|
|
60
94
|
onMouseEnter?.(event);
|
package/src/metadata.tsx
CHANGED
|
@@ -3,7 +3,11 @@
|
|
|
3
3
|
|
|
4
4
|
import { Fragment } from 'react';
|
|
5
5
|
|
|
6
|
-
/**
|
|
6
|
+
/**
|
|
7
|
+
* A title, a layout's `template` (`'%s · Site'`) and `default`, or an `absolute` title that skips templates. A
|
|
8
|
+
* `default`, on a layout or a page, goes through the nearest `template` of the layouts above it like a string title,
|
|
9
|
+
* never through the one beside it; a layout's `default` is also the title of the pages below it that set none.
|
|
10
|
+
*/
|
|
7
11
|
export type MetadataTitle = string | { default?: string; template?: string; absolute?: string };
|
|
8
12
|
|
|
9
13
|
/** An image for a link preview: `og:image` with `og:image:width`, `og:image:height` and `og:image:alt` when given, or `twitter:image` with `twitter:image:alt`. */
|
|
@@ -48,12 +52,18 @@ export type ResolvedMetadata = Omit<Metadata, 'title' | 'openGraph' | 'twitter'>
|
|
|
48
52
|
twitter?: Omit<Twitter, 'images'> & { images?: ResolvedImage[] };
|
|
49
53
|
};
|
|
50
54
|
|
|
55
|
+
/**
|
|
56
|
+
* The title that `title` stands for, given the template from the layouts above it. A string and a `default` go
|
|
57
|
+
* through the template, an `absolute` title does not, and an object with no `default` and no `absolute` (a layout
|
|
58
|
+
* that only sets a template) has no title of its own.
|
|
59
|
+
*/
|
|
51
60
|
function titleOf(title: MetadataTitle | undefined, template: string | undefined): string | undefined {
|
|
52
61
|
if (title === undefined) return undefined;
|
|
53
62
|
// A function replacer: a title such as "Save $& now" must not be read as a replacement pattern.
|
|
54
|
-
|
|
63
|
+
const inTemplate = (text: string) => (template ? template.replace('%s', () => text) : text);
|
|
64
|
+
if (typeof title === 'string') return inTemplate(title);
|
|
55
65
|
if (title.absolute !== undefined) return title.absolute;
|
|
56
|
-
return title.default;
|
|
66
|
+
return title.default === undefined ? undefined : inTemplate(title.default);
|
|
57
67
|
}
|
|
58
68
|
|
|
59
69
|
/** The images as a list of descriptors with string URLs; like Next.js, a null image or one without a URL is left out. */
|
|
@@ -72,7 +82,9 @@ function withImages<T extends { images?: MetadataImages }>(group: T): Omit<T, 'i
|
|
|
72
82
|
|
|
73
83
|
/**
|
|
74
84
|
* Merges the layouts' metadata (outermost first), the page's, and the server's. A layout's `title.template` applies
|
|
75
|
-
* to titles below it
|
|
85
|
+
* to the titles below it. `title.default`, on a layout or a page, goes through the templates above it like a string
|
|
86
|
+
* title and never through its own; on a layout it is the title when nothing below sets one. `title.absolute` skips
|
|
87
|
+
* templates.
|
|
76
88
|
*/
|
|
77
89
|
export function resolveMetadata(layouts: readonly (Metadata | undefined)[], page: Metadata | undefined, server?: Metadata): ResolvedMetadata {
|
|
78
90
|
let resolved: ResolvedMetadata = {};
|
|
@@ -82,8 +94,9 @@ export function resolveMetadata(layouts: readonly (Metadata | undefined)[], page
|
|
|
82
94
|
const { title, openGraph, twitter, alternates, icons, other, ...rest } = metadata;
|
|
83
95
|
resolved = { ...resolved, ...rest };
|
|
84
96
|
if (title !== undefined) {
|
|
85
|
-
//
|
|
86
|
-
|
|
97
|
+
// The template from above applies to every title but an absolute one, a default included. This title's own
|
|
98
|
+
// template is stored after its title is written, so it applies only to the titles below.
|
|
99
|
+
const own = titleOf(title, template);
|
|
87
100
|
if (own !== undefined) resolved.title = own;
|
|
88
101
|
if (typeof title === 'object' && title.template) template = title.template;
|
|
89
102
|
}
|
package/src/modules.ts
CHANGED
|
@@ -6,8 +6,21 @@ export type PageComponent = ComponentType<Record<string, unknown>>;
|
|
|
6
6
|
/** The props every layout gets: its `children` and the route `params`. The loader's props and parallel route slots arrive as further props. */
|
|
7
7
|
export type LayoutProps = { children: ReactNode; params: Params };
|
|
8
8
|
export type LayoutComponent = ComponentType<LayoutProps & Record<string, unknown>>;
|
|
9
|
-
/**
|
|
10
|
-
|
|
9
|
+
/**
|
|
10
|
+
* The props of an `error.tsx`: what was thrown, and a way to try again.
|
|
11
|
+
*
|
|
12
|
+
* - `error.status` is the HTTP status of a server answer behind the error: the status of the error page the server
|
|
13
|
+
* rendered, or of a server action call that failed. An error thrown in the browser has none.
|
|
14
|
+
* - `error.withheld` is true when the message is Netjes's stand-in for one it does not show: the server's reason
|
|
15
|
+
* phrase for an exception while error details are off, "Something went wrong" for a `Page.Defer` failure the server
|
|
16
|
+
* withheld or a thrown value that has no message, or Netjes's own text for a server action whose answer had no
|
|
17
|
+
* message. Render `error.message` only when `!error.withheld`.
|
|
18
|
+
* - `error.stack` is the server's stack when error details are on, and undefined for a server error sent without one.
|
|
19
|
+
* - `reset()` renders the segment again after an error a segment's boundary caught. On an error page the server
|
|
20
|
+
* rendered it loads the page from the server again (`router.refresh()`), and on the page the router's own boundary
|
|
21
|
+
* shows it does nothing: offer a link or a full reload there.
|
|
22
|
+
*/
|
|
23
|
+
export type ErrorPageProps = { error: Error & { status?: number; withheld?: boolean }; reset: () => void };
|
|
11
24
|
|
|
12
25
|
export type LoadedSegment = {
|
|
13
26
|
id: string;
|
package/src/mounted.tsx
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { type ReactNode, useMemo } from 'react';
|
|
2
|
+
import { Form, type FormAction, type FormProps, SubmitButton, type SubmitButtonProps } from './form.tsx';
|
|
3
|
+
import { type Href, isHrefShape } from './href.ts';
|
|
4
|
+
import { Link, type LinkProps } from './link.tsx';
|
|
5
|
+
import { isDotSegment } from './payload.ts';
|
|
6
|
+
import { type Router, useHref, usePagePayload, usePathname, useRouter } from './router.tsx';
|
|
7
|
+
|
|
8
|
+
/** The props of a page package's `<Link>`: those of the core `<Link>`, with an href below the package's mount. */
|
|
9
|
+
export type MountedLinkProps<THref extends string = string> = Omit<LinkProps, 'href'> & { href: THref };
|
|
10
|
+
|
|
11
|
+
/** The props of a page package's `<Form>`: those of the core `<Form>`, with a URL `action` below the package's mount. */
|
|
12
|
+
export type MountedFormProps<THref extends string = string> = Omit<FormProps, 'action'> & { action?: THref | FormAction };
|
|
13
|
+
|
|
14
|
+
/** The props of a page package's `<SubmitButton>`, with a URL `formAction` below the package's mount. */
|
|
15
|
+
export type MountedSubmitButtonProps<THref extends string = string> = Omit<SubmitButtonProps, 'formAction'> & {
|
|
16
|
+
formAction?: THref | Exclude<SubmitButtonProps['formAction'], string>;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
/** The client router, as a page package's `useRouter()` returns it: `push`, `replace` and `prefetch` go below its mount. */
|
|
20
|
+
export type MountedRouter<THref extends string = string> = Omit<Router, 'push' | 'replace' | 'prefetch'> & {
|
|
21
|
+
push(href: THref, options?: { scroll?: boolean }): Promise<void>;
|
|
22
|
+
replace(href: THref, options?: { scroll?: boolean }): Promise<void>;
|
|
23
|
+
prefetch(href: THref): void;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/** What {@link mounted} returns: the links, forms and router hooks of one page package. */
|
|
27
|
+
export type Mounted<THref extends string = string> = {
|
|
28
|
+
/** A `<Link>` whose href is below the mount: `/articles` goes to `/help/articles` for a package mounted at `/help`. */
|
|
29
|
+
Link: (props: MountedLinkProps<THref>) => ReactNode;
|
|
30
|
+
/** A `<Form>` whose URL `action` is below the mount. Without one it posts to the page on screen, as the core `<Form>`. */
|
|
31
|
+
Form: (props: MountedFormProps<THref>) => ReactNode;
|
|
32
|
+
/** A `<SubmitButton>` whose URL `formAction` is below the mount. */
|
|
33
|
+
SubmitButton: (props: MountedSubmitButtonProps<THref>) => ReactNode;
|
|
34
|
+
/** The client router, whose `push`, `replace` and `prefetch` take hrefs below the mount. */
|
|
35
|
+
useRouter: () => MountedRouter<THref>;
|
|
36
|
+
/**
|
|
37
|
+
* The path of the page on screen below the mount, without the base path: `/articles/x` for `/help/articles/x`, and
|
|
38
|
+
* `/` for the mount itself. A page outside the mount gets its whole path, as the core `usePathname` gives it.
|
|
39
|
+
*/
|
|
40
|
+
usePathname: () => string;
|
|
41
|
+
/**
|
|
42
|
+
* An href below the mount, under the base path, for a plain `<a>`, another attribute or a `fetch`: a page's, or an
|
|
43
|
+
* endpoint's from the package's `endpointUrl()`. Untyped, as the core `useHref`.
|
|
44
|
+
*/
|
|
45
|
+
useHref: (href: string) => string;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
/** The package's URL for the page on screen, from the payload: null when the page has no value for the prefix. */
|
|
49
|
+
function useMountOrNull(name: string): string | null {
|
|
50
|
+
const mounts = usePagePayload().mounts;
|
|
51
|
+
const mount = mounts && Object.hasOwn(mounts, name) ? mounts[name] : undefined;
|
|
52
|
+
if (mount === undefined) {
|
|
53
|
+
throw new Error(`netjes: the page package '${name}' is not mounted: map it with app.MapPagePackage(...) before app.MapPages()`);
|
|
54
|
+
}
|
|
55
|
+
return mount;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The package's URL for the page on screen; throws when the page has none. */
|
|
59
|
+
function useMount(name: string): string {
|
|
60
|
+
const mount = useMountOrNull(name);
|
|
61
|
+
if (mount === null) throw new Error(`netjes: '${name}' is mounted at a prefix with a value, and this page has none for it`);
|
|
62
|
+
return mount;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* A segment as routing compares it: decoded where it can be, as the server decodes a path, which leaves `%2F` as it is
|
|
67
|
+
* (so `a%2Fb` and `a%252Fb` hold the same value), in any case.
|
|
68
|
+
*/
|
|
69
|
+
function comparable(segment: string): string {
|
|
70
|
+
try {
|
|
71
|
+
return decodeURIComponent(segment.replace(/%2F/gi, '%252F')).toLowerCase();
|
|
72
|
+
} catch {
|
|
73
|
+
return segment.toLowerCase();
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** `pathname` without the mount in front, `/` for the mount itself; the whole path when it is not below the mount. */
|
|
78
|
+
function belowMount(pathname: string, mount: string | null): string {
|
|
79
|
+
if (mount === null || mount === '/') return pathname;
|
|
80
|
+
const prefix = mount.split('/').slice(1);
|
|
81
|
+
const segments = pathname.split('/').slice(1);
|
|
82
|
+
if (segments.length < prefix.length || prefix.some((segment, i) => comparable(segment) !== comparable(segments[i] ?? ''))) return pathname;
|
|
83
|
+
const rest = segments.slice(prefix.length).join('/');
|
|
84
|
+
return rest === '' ? '/' : `/${rest}`;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* `href` below `mount`: a path gets the mount in front, and a link within the page on screen (`?…`, `#…`) passes
|
|
89
|
+
* through. Anything else throws, as does a path with a dot segment, which would climb out of the mount.
|
|
90
|
+
*/
|
|
91
|
+
function underMount(href: string, mount: string, name: string): string {
|
|
92
|
+
const withinThePage = href.startsWith('?') || href.startsWith('#');
|
|
93
|
+
const path = href.split(/[?#]/, 1)[0] ?? '';
|
|
94
|
+
// Browsers read a backslash in a path as a slash, and %2e as a dot.
|
|
95
|
+
if (!isHrefShape(href) || (!withinThePage && (!href.startsWith('/') || path.split(/[/\\]/).some(isDotSegment)))) {
|
|
96
|
+
throw new Error(
|
|
97
|
+
`netjes: '${href}' is no link below the mount of '${name}': start it with '/' (but not '//' or '/\\'), with no '.' or ` +
|
|
98
|
+
"'..' segment, or with '?' or '#'. Link to another site, or elsewhere in the app, with the Link from 'netjes'.",
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
if (withinThePage || mount === '/') return href;
|
|
102
|
+
return href === '/' || href[1] === '?' || href[1] === '#' ? mount + href.slice(1) : mount + href;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* The links, forms and router hooks of the page package `name`, its npm name, bound to where the app mounted it. Each
|
|
107
|
+
* puts the package's URL for the page on screen in front of its hrefs, and the base path in front of that, so a
|
|
108
|
+
* package links to its own pages as if it were mounted at the root. A package's generated file calls it once:
|
|
109
|
+
* `export const { Link, Form, SubmitButton, useRouter, usePathname, useHref } = mounted<MountHref>('@acme/help-center')`.
|
|
110
|
+
*/
|
|
111
|
+
export function mounted<THref extends string = string>(name: string): Mounted<THref> {
|
|
112
|
+
function MountedLink({ href, ...rest }: MountedLinkProps<THref>) {
|
|
113
|
+
const mount = useMount(name);
|
|
114
|
+
return <Link href={underMount(href, mount, name) as Href} {...rest} />;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function MountedForm({ action, ...rest }: MountedFormProps<THref>) {
|
|
118
|
+
const mount = useMount(name);
|
|
119
|
+
const url = typeof action === 'string' ? underMount(action, mount, name) : action;
|
|
120
|
+
return <Form {...(url === undefined ? {} : { action: url })} {...rest} />;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function MountedSubmitButton({ formAction, ...rest }: MountedSubmitButtonProps<THref>) {
|
|
124
|
+
const mount = useMount(name);
|
|
125
|
+
return <SubmitButton formAction={typeof formAction === 'string' ? underMount(formAction, mount, name) : formAction} {...rest} />;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function useMountedRouter(): MountedRouter<THref> {
|
|
129
|
+
const mount = useMount(name);
|
|
130
|
+
const router = useRouter();
|
|
131
|
+
return useMemo(
|
|
132
|
+
() => ({
|
|
133
|
+
push: (href, options) => router.push(underMount(href, mount, name) as Href, options),
|
|
134
|
+
replace: (href, options) => router.replace(underMount(href, mount, name) as Href, options),
|
|
135
|
+
prefetch: (href) => router.prefetch(underMount(href, mount, name) as Href),
|
|
136
|
+
refresh: () => router.refresh(),
|
|
137
|
+
back: () => router.back(),
|
|
138
|
+
forward: () => router.forward(),
|
|
139
|
+
}),
|
|
140
|
+
[router, mount],
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function useMountedPathname(): string {
|
|
145
|
+
return belowMount(usePathname(), useMountOrNull(name));
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function useMountedHref(href: string): string {
|
|
149
|
+
return useHref(underMount(href, useMount(name), name));
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return {
|
|
153
|
+
Link: MountedLink,
|
|
154
|
+
Form: MountedForm,
|
|
155
|
+
SubmitButton: MountedSubmitButton,
|
|
156
|
+
useRouter: useMountedRouter,
|
|
157
|
+
usePathname: useMountedPathname,
|
|
158
|
+
useHref: useMountedHref,
|
|
159
|
+
};
|
|
160
|
+
}
|