@alepha/react 0.7.0 → 0.7.2

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.
Files changed (37) hide show
  1. package/README.md +1 -1
  2. package/dist/index.browser.cjs +59 -22
  3. package/dist/index.browser.js +42 -6
  4. package/dist/index.cjs +152 -85
  5. package/dist/index.d.ts +317 -206
  6. package/dist/index.js +130 -64
  7. package/dist/{useActive-DjpZBEuB.cjs → useRouterState-C2uo0jXu.cjs} +319 -140
  8. package/dist/{useActive-BX41CqY8.js → useRouterState-D5__ZcUV.js} +321 -143
  9. package/package.json +11 -10
  10. package/src/components/ClientOnly.tsx +35 -0
  11. package/src/components/ErrorBoundary.tsx +1 -1
  12. package/src/components/ErrorViewer.tsx +161 -0
  13. package/src/components/Link.tsx +9 -3
  14. package/src/components/NestedView.tsx +18 -3
  15. package/src/components/NotFound.tsx +30 -0
  16. package/src/descriptors/$page.ts +141 -30
  17. package/src/errors/RedirectionError.ts +4 -1
  18. package/src/hooks/RouterHookApi.ts +42 -24
  19. package/src/hooks/useAlepha.ts +12 -0
  20. package/src/hooks/useClient.ts +8 -6
  21. package/src/hooks/useInject.ts +2 -2
  22. package/src/hooks/useQueryParams.ts +1 -1
  23. package/src/hooks/useRouter.ts +6 -0
  24. package/src/index.browser.ts +4 -2
  25. package/src/index.shared.ts +11 -5
  26. package/src/index.ts +3 -4
  27. package/src/providers/BrowserRouterProvider.ts +4 -3
  28. package/src/providers/PageDescriptorProvider.ts +91 -20
  29. package/src/providers/ReactBrowserProvider.ts +6 -59
  30. package/src/providers/ReactBrowserRenderer.ts +72 -0
  31. package/src/providers/ReactServerProvider.ts +200 -81
  32. package/dist/index.browser.cjs.map +0 -1
  33. package/dist/index.browser.js.map +0 -1
  34. package/dist/index.cjs.map +0 -1
  35. package/dist/index.js.map +0 -1
  36. package/dist/useActive-BX41CqY8.js.map +0 -1
  37. package/dist/useActive-DjpZBEuB.cjs.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alepha/react",
3
- "version": "0.7.0",
3
+ "version": "0.7.2",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "main": "./dist/index.js",
@@ -13,25 +13,26 @@
13
13
  "src"
14
14
  ],
15
15
  "dependencies": {
16
- "@alepha/core": "0.7.0",
17
- "@alepha/router": "0.7.0",
18
- "@alepha/server": "0.7.0",
19
- "@alepha/server-static": "0.7.0",
16
+ "@alepha/core": "0.7.2",
17
+ "@alepha/router": "0.7.2",
18
+ "@alepha/server": "0.7.2",
19
+ "@alepha/server-static": "0.7.2",
20
20
  "react-dom": "^19.1.0"
21
21
  },
22
22
  "devDependencies": {
23
- "@types/react": "^19.1.6",
24
- "@types/react-dom": "^19.1.5",
25
- "pkgroll": "^2.12.2",
23
+ "@types/react": "^19.1.8",
24
+ "@types/react-dom": "^19.1.6",
25
+ "pkgroll": "^2.13.1",
26
26
  "react": "^19.1.0",
27
- "vitest": "^3.1.4"
27
+ "vitest": "^3.2.4"
28
28
  },
29
29
  "peerDependencies": {
30
30
  "@types/react": "^19",
31
31
  "react": "^19"
32
32
  },
33
33
  "scripts": {
34
- "build": "pkgroll --clean-dist --sourcemap"
34
+ "test": "vitest run",
35
+ "build": "pkgroll --clean-dist"
35
36
  },
36
37
  "homepage": "https://github.com/feunard/alepha",
37
38
  "repository": {
@@ -0,0 +1,35 @@
1
+ import {
2
+ type PropsWithChildren,
3
+ type ReactNode,
4
+ useEffect,
5
+ useState,
6
+ } from "react";
7
+
8
+ export interface ClientOnlyProps {
9
+ fallback?: ReactNode;
10
+ disabled?: boolean;
11
+ }
12
+
13
+ /**
14
+ * A small utility component that renders its children only on the client side.
15
+ *
16
+ * Optionally, you can provide a fallback React node that will be rendered.
17
+ *
18
+ * You should use this component when
19
+ * - you have code that relies on browser-specific APIs
20
+ * - you want to avoid server-side rendering for a specific part of your application
21
+ * - you want to prevent pre-rendering of a component
22
+ */
23
+ const ClientOnly = (props: PropsWithChildren<ClientOnlyProps>) => {
24
+ const [mounted, setMounted] = useState(false);
25
+
26
+ useEffect(() => setMounted(true), []);
27
+
28
+ if (props.disabled) {
29
+ return props.children;
30
+ }
31
+
32
+ return mounted ? props.children : props.fallback;
33
+ };
34
+
35
+ export default ClientOnly;
@@ -1,7 +1,7 @@
1
1
  import React, {
2
- type ReactNode,
3
2
  type ErrorInfo,
4
3
  type PropsWithChildren,
4
+ type ReactNode,
5
5
  } from "react";
6
6
 
7
7
  /**
@@ -0,0 +1,161 @@
1
+ import { useState } from "react";
2
+ import { useAlepha } from "../hooks/useAlepha.ts";
3
+
4
+ interface ErrorViewerProps {
5
+ error: Error;
6
+ }
7
+
8
+ // TODO: design this better
9
+
10
+ const ErrorViewer = ({ error }: ErrorViewerProps) => {
11
+ const [expanded, setExpanded] = useState(false);
12
+ const isProduction = useAlepha().isProduction();
13
+ // const status = isHttpError(error) ? error.status : 500;
14
+
15
+ if (isProduction) {
16
+ return <ErrorViewerProduction />;
17
+ }
18
+
19
+ const stackLines = error.stack?.split("\n") ?? [];
20
+ const previewLines = stackLines.slice(0, 5);
21
+ const hiddenLineCount = stackLines.length - previewLines.length;
22
+
23
+ const copyToClipboard = (text: string) => {
24
+ navigator.clipboard.writeText(text).catch((err) => {
25
+ console.error("Clipboard error:", err);
26
+ });
27
+ };
28
+
29
+ const styles = {
30
+ container: {
31
+ padding: "24px",
32
+ backgroundColor: "#FEF2F2",
33
+ color: "#7F1D1D",
34
+ border: "1px solid #FECACA",
35
+ borderRadius: "16px",
36
+ boxShadow: "0 8px 24px rgba(0,0,0,0.05)",
37
+ fontFamily: "monospace",
38
+ maxWidth: "768px",
39
+ margin: "40px auto",
40
+ },
41
+ heading: {
42
+ fontSize: "20px",
43
+ fontWeight: "bold",
44
+ marginBottom: "4px",
45
+ },
46
+ name: {
47
+ fontSize: "16px",
48
+ fontWeight: 600,
49
+ },
50
+ message: {
51
+ fontSize: "14px",
52
+ marginBottom: "16px",
53
+ },
54
+ sectionHeader: {
55
+ display: "flex",
56
+ justifyContent: "space-between",
57
+ alignItems: "center",
58
+ fontSize: "12px",
59
+ marginBottom: "4px",
60
+ color: "#991B1B",
61
+ },
62
+ copyButton: {
63
+ fontSize: "12px",
64
+ color: "#DC2626",
65
+ background: "none",
66
+ border: "none",
67
+ cursor: "pointer",
68
+ textDecoration: "underline",
69
+ },
70
+ stackContainer: {
71
+ backgroundColor: "#FEE2E2",
72
+ padding: "12px",
73
+ borderRadius: "8px",
74
+ fontSize: "13px",
75
+ lineHeight: "1.4",
76
+ overflowX: "auto" as const,
77
+ whiteSpace: "pre-wrap" as const,
78
+ },
79
+ expandLine: {
80
+ color: "#F87171",
81
+ cursor: "pointer",
82
+ marginTop: "8px",
83
+ },
84
+ };
85
+
86
+ return (
87
+ <div style={styles.container}>
88
+ <div>
89
+ <div style={styles.heading}>🔥 Error</div>
90
+ <div style={styles.name}>{error.name}</div>
91
+ <div style={styles.message}>{error.message}</div>
92
+ </div>
93
+
94
+ {stackLines.length > 0 && (
95
+ <div>
96
+ <div style={styles.sectionHeader}>
97
+ <span>Stack trace</span>
98
+ <button
99
+ onClick={() => copyToClipboard(error.stack!)}
100
+ style={styles.copyButton}
101
+ >
102
+ Copy all
103
+ </button>
104
+ </div>
105
+ <pre style={styles.stackContainer}>
106
+ {(expanded ? stackLines : previewLines).map((line, i) => (
107
+ <div key={i}>{line}</div>
108
+ ))}
109
+ {!expanded && hiddenLineCount > 0 && (
110
+ <div style={styles.expandLine} onClick={() => setExpanded(true)}>
111
+ + {hiddenLineCount} more lines...
112
+ </div>
113
+ )}
114
+ </pre>
115
+ </div>
116
+ )}
117
+ </div>
118
+ );
119
+ };
120
+
121
+ export default ErrorViewer;
122
+
123
+ const ErrorViewerProduction = () => {
124
+ const styles = {
125
+ container: {
126
+ padding: "24px",
127
+ backgroundColor: "#FEF2F2",
128
+ color: "#7F1D1D",
129
+ border: "1px solid #FECACA",
130
+ borderRadius: "16px",
131
+ boxShadow: "0 8px 24px rgba(0,0,0,0.05)",
132
+ fontFamily: "monospace",
133
+ maxWidth: "768px",
134
+ margin: "40px auto",
135
+ textAlign: "center" as const,
136
+ },
137
+ heading: {
138
+ fontSize: "20px",
139
+ fontWeight: "bold",
140
+ marginBottom: "8px",
141
+ },
142
+ name: {
143
+ fontSize: "16px",
144
+ fontWeight: 600,
145
+ marginBottom: "4px",
146
+ },
147
+ message: {
148
+ fontSize: "14px",
149
+ opacity: 0.85,
150
+ },
151
+ };
152
+
153
+ return (
154
+ <div style={styles.container}>
155
+ <div style={styles.heading}>🚨 An error occurred</div>
156
+ <div style={styles.message}>
157
+ Something went wrong. Please try again later.
158
+ </div>
159
+ </div>
160
+ );
161
+ };
@@ -1,6 +1,6 @@
1
1
  import { OPTIONS } from "@alepha/core";
2
- import React from "react";
3
2
  import type { AnchorHTMLAttributes } from "react";
3
+ import React from "react";
4
4
  import { RouterContext } from "../contexts/RouterContext.ts";
5
5
  import type { PageDescriptor } from "../descriptors/$page.ts";
6
6
  import { useRouter } from "../hooks/useRouter.ts";
@@ -13,6 +13,8 @@ export interface LinkProps extends AnchorHTMLAttributes<HTMLAnchorElement> {
13
13
  const Link = (props: LinkProps) => {
14
14
  React.useContext(RouterContext);
15
15
 
16
+ const router = useRouter();
17
+
16
18
  const to = typeof props.to === "string" ? props.to : props.to[OPTIONS].path;
17
19
  if (!to) {
18
20
  return null;
@@ -26,9 +28,13 @@ const Link = (props: LinkProps) => {
26
28
  const name =
27
29
  typeof props.to === "string" ? undefined : props.to[OPTIONS].name;
28
30
 
29
- const router = useRouter();
31
+ const anchorProps = {
32
+ ...props,
33
+ to: undefined,
34
+ };
35
+
30
36
  return (
31
- <a {...router.anchor(to)} {...props}>
37
+ <a {...router.anchor(to)} {...anchorProps}>
32
38
  {props.children ?? name}
33
39
  </a>
34
40
  );
@@ -10,10 +10,25 @@ export interface NestedViewProps {
10
10
  }
11
11
 
12
12
  /**
13
- * Nested view component
13
+ * A component that renders the current view of the nested router layer.
14
14
  *
15
- * @param props
16
- * @constructor
15
+ * To be simple, it renders the `element` of the current child page of a parent page.
16
+ *
17
+ * @example
18
+ * ```tsx
19
+ * import { NestedView } from "@alepha/react";
20
+ *
21
+ * class App {
22
+ * parent = $page({
23
+ * component: () => <NestedView />,
24
+ * });
25
+ *
26
+ * child = $page({
27
+ * parent: this.root,
28
+ * component: () => <div>Child Page</div>,
29
+ * });
30
+ * }
31
+ * ```
17
32
  */
18
33
  const NestedView = (props: NestedViewProps) => {
19
34
  const app = useContext(RouterContext);
@@ -0,0 +1,30 @@
1
+ export default function NotFoundPage() {
2
+ return (
3
+ <div
4
+ style={{
5
+ height: "100vh",
6
+ display: "flex",
7
+ flexDirection: "column",
8
+ justifyContent: "center",
9
+ alignItems: "center",
10
+ textAlign: "center",
11
+ fontFamily: "sans-serif",
12
+ padding: "1rem",
13
+ }}
14
+ >
15
+ <h1 style={{ fontSize: "1rem", marginBottom: "0.5rem" }}>
16
+ This page does not exist
17
+ </h1>
18
+ <a
19
+ href="/"
20
+ style={{
21
+ fontSize: "0.7rem",
22
+ color: "#007bff",
23
+ textDecoration: "none",
24
+ }}
25
+ >
26
+ ← Back to home
27
+ </a>
28
+ </div>
29
+ );
30
+ }
@@ -1,7 +1,15 @@
1
- import { type Async, OPTIONS, type Static, type TSchema } from "@alepha/core";
2
- import { KIND, NotImplementedError, __descriptor } from "@alepha/core";
1
+ import {
2
+ __descriptor,
3
+ type Async,
4
+ KIND,
5
+ NotImplementedError,
6
+ OPTIONS,
7
+ type Static,
8
+ type TSchema,
9
+ } from "@alepha/core";
10
+ import type { ServerRequest, ServerRoute } from "@alepha/server";
3
11
  import type { FC, ReactNode } from "react";
4
- import type { RouterHookApi } from "../hooks/RouterHookApi.ts";
12
+ import type { ClientOnlyProps } from "../components/ClientOnly.tsx";
5
13
  import type { PageReactContext } from "../providers/PageDescriptorProvider.ts";
6
14
 
7
15
  const KEY = "PAGE";
@@ -13,34 +21,102 @@ export interface PageConfigSchema {
13
21
 
14
22
  export type TPropsDefault = any;
15
23
 
16
- export type TPropsParentDefault = object;
24
+ export type TPropsParentDefault = {};
17
25
 
18
26
  export interface PageDescriptorOptions<
19
27
  TConfig extends PageConfigSchema = PageConfigSchema,
20
28
  TProps extends object = TPropsDefault,
21
29
  TPropsParent extends object = TPropsParentDefault,
22
- > {
30
+ > extends Pick<ServerRoute, "cache"> {
31
+ /**
32
+ * Name your page.
33
+ *
34
+ * @default Descriptor key
35
+ */
23
36
  name?: string;
24
37
 
38
+ /**
39
+ * Optional description of the page.
40
+ */
41
+ description?: string;
42
+
43
+ /**
44
+ * Add a pathname to the page.
45
+ *
46
+ * Pathname can contain parameters, like `/post/:slug`.
47
+ *
48
+ * @default ""
49
+ */
25
50
  path?: string;
26
51
 
52
+ /**
53
+ * Add an input schema to define:
54
+ * - `params`: parameters from the pathname.
55
+ * - `query`: query parameters from the URL.
56
+ */
27
57
  schema?: TConfig;
28
58
 
29
- resolve?: (config: PageResolve<TConfig, TPropsParent>) => Async<TProps>;
30
-
59
+ /**
60
+ * Load data before rendering the page.
61
+ *
62
+ * This function receives
63
+ * - the request context and
64
+ * - the parent props (if page has a parent)
65
+ *
66
+ * In SSR, the returned data will be serialized and sent to the client, then reused during the client-side hydration.
67
+ *
68
+ * Resolve can be stopped by throwing an error, which will be handled by the `errorHandler` function.
69
+ * It's common to throw a `NotFoundError` to display a 404 page.
70
+ *
71
+ * RedirectError can be thrown to redirect the user to another page.
72
+ */
73
+ resolve?: (context: PageResolve<TConfig, TPropsParent>) => Async<TProps>;
74
+
75
+ /**
76
+ * The component to render when the page is loaded.
77
+ *
78
+ * If `lazy` is defined, this will be ignored.
79
+ * Prefer using `lazy` to improve the initial loading time.
80
+ */
31
81
  component?: FC<TProps & TPropsParent>;
32
82
 
83
+ /**
84
+ * Lazy load the component when the page is loaded.
85
+ *
86
+ * It's recommended to use this for components to improve the initial loading time
87
+ * and enable code-splitting.
88
+ */
33
89
  lazy?: () => Promise<{ default: FC<TProps & TPropsParent> }>;
34
90
 
91
+ /**
92
+ * Set some children pages and make the page a parent page.
93
+ *
94
+ * /!\ Parent page can't be rendered directly. /!\
95
+ *
96
+ * If you still want to render at this pathname, add a child page with an empty path.
97
+ */
35
98
  children?: Array<{ [OPTIONS]: PageDescriptorOptions }>;
36
99
 
37
- parent?: { [OPTIONS]: PageDescriptorOptions<any, TPropsParent> };
100
+ parent?: { [OPTIONS]: PageDescriptorOptions<PageConfigSchema, TPropsParent> };
38
101
 
39
102
  can?: () => boolean;
40
103
 
41
104
  head?: Head | ((props: TProps, previous?: Head) => Head);
42
105
 
43
106
  errorHandler?: (error: Error) => ReactNode;
107
+
108
+ prerender?:
109
+ | boolean
110
+ | {
111
+ entries?: Array<Partial<PageRequestConfig<TConfig>>>;
112
+ };
113
+
114
+ /**
115
+ * If true, the page will be rendered on the client-side.
116
+ */
117
+ client?: boolean | ClientOnlyProps;
118
+
119
+ afterHandler?: (request: ServerRequest) => any;
44
120
  }
45
121
 
46
122
  export interface PageDescriptor<
@@ -51,18 +127,18 @@ export interface PageDescriptor<
51
127
  [KIND]: typeof KEY;
52
128
  [OPTIONS]: PageDescriptorOptions<TConfig, TProps, TPropsParent>;
53
129
 
54
- render: (options?: {
55
- params?: Record<string, string>;
56
- query?: Record<string, string>;
57
- }) => Promise<string>;
58
- go: () => void;
59
- createAnchorProps: (routerHook: RouterHookApi) => {
60
- href: string;
61
- onClick: () => void;
62
- };
63
- can: () => boolean;
130
+ /**
131
+ * For testing or build purposes, this will render the page (with or without the HTML layout) and return the HTML and context.
132
+ * Only valid for server-side rendering, it will throw an error if called on the client-side.
133
+ */
134
+ render: (
135
+ options?: PageDescriptorRenderOptions,
136
+ ) => Promise<PageDescriptorRenderResult>;
64
137
  }
65
138
 
139
+ /**
140
+ * Main descriptor for defining a React route in the application.
141
+ */
66
142
  export const $page = <
67
143
  TConfig extends PageConfigSchema = PageConfigSchema,
68
144
  TProps extends object = TPropsDefault,
@@ -93,18 +169,6 @@ export const $page = <
93
169
  render: () => {
94
170
  throw new NotImplementedError(KEY);
95
171
  },
96
- go: () => {
97
- throw new NotImplementedError(KEY);
98
- },
99
- createAnchorProps: () => {
100
- throw new NotImplementedError(KEY);
101
- },
102
- can: () => {
103
- if (options.can) {
104
- return options.can();
105
- }
106
- return true;
107
- },
108
172
  };
109
173
  };
110
174
 
@@ -112,12 +176,59 @@ $page[KIND] = KEY;
112
176
 
113
177
  // ---------------------------------------------------------------------------------------------------------------------
114
178
 
179
+ export interface PageDescriptorRenderOptions {
180
+ params?: Record<string, string>;
181
+ query?: Record<string, string>;
182
+ withLayout?: boolean;
183
+ }
184
+
185
+ export interface PageDescriptorRenderResult {
186
+ html: string;
187
+ context: PageReactContext;
188
+ }
189
+
115
190
  export interface Head {
116
191
  title?: string;
192
+ description?: string;
117
193
  titleSeparator?: string;
118
194
  htmlAttributes?: Record<string, string>;
119
195
  bodyAttributes?: Record<string, string>;
120
196
  meta?: Array<{ name: string; content: string }>;
197
+
198
+ // TODO
199
+ keywords?: string[];
200
+ author?: string;
201
+ robots?: string;
202
+ themeColor?: string;
203
+ viewport?:
204
+ | string
205
+ | {
206
+ width?: string;
207
+ height?: string;
208
+ initialScale?: string;
209
+ maximumScale?: string;
210
+ userScalable?: "no" | "yes" | "0" | "1";
211
+ interactiveWidget?:
212
+ | "resizes-visual"
213
+ | "resizes-content"
214
+ | "overlays-content";
215
+ };
216
+
217
+ og?: {
218
+ title?: string;
219
+ description?: string;
220
+ image?: string;
221
+ url?: string;
222
+ type?: string;
223
+ };
224
+
225
+ twitter?: {
226
+ card?: string;
227
+ title?: string;
228
+ description?: string;
229
+ image?: string;
230
+ site?: string;
231
+ };
121
232
  }
122
233
 
123
234
  export interface PageRequestConfig<
@@ -1,7 +1,10 @@
1
1
  import type { HrefLike } from "../hooks/RouterHookApi.ts";
2
2
 
3
3
  export class RedirectionError extends Error {
4
- constructor(public readonly page: HrefLike) {
4
+ public readonly page: HrefLike;
5
+
6
+ constructor(page: HrefLike) {
5
7
  super("Redirection");
8
+ this.page = page;
6
9
  }
7
10
  }