@alepha/react 0.6.0 → 0.6.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.
@@ -1,15 +0,0 @@
1
- import type { Alepha } from "@alepha/core";
2
- import { createContext } from "react";
3
- import type { PageContext } from "../descriptors/$page";
4
- import type { Router, RouterState } from "../services/Router";
5
-
6
- export interface RouterContextValue {
7
- router: Router;
8
- alepha: Alepha;
9
- state: RouterState;
10
- args: PageContext;
11
- }
12
-
13
- export const RouterContext = createContext<RouterContextValue | undefined>(
14
- undefined,
15
- );
@@ -1,10 +0,0 @@
1
- import { createContext } from "react";
2
-
3
- export interface RouterLayerContextValue {
4
- index: number;
5
- path: string;
6
- }
7
-
8
- export const RouterLayerContext = createContext<
9
- RouterLayerContextValue | undefined
10
- >(undefined);
@@ -1,28 +0,0 @@
1
- import { KIND, __descriptor } from "@alepha/core";
2
-
3
- const KEY = "AUTH";
4
-
5
- export interface AuthDescriptorOptions {
6
- name?: string;
7
- oidc?: {
8
- issuer: string;
9
- clientId: string;
10
- clientSecret?: string;
11
- redirectUri?: string;
12
- };
13
- }
14
-
15
- export interface AuthDescriptor {
16
- [KIND]: typeof KEY;
17
- options: AuthDescriptorOptions;
18
- }
19
-
20
- export const $auth = (options: AuthDescriptorOptions): AuthDescriptor => {
21
- __descriptor(KEY);
22
- return {
23
- [KIND]: KEY,
24
- options,
25
- };
26
- };
27
-
28
- $auth[KIND] = KEY;
@@ -1,144 +0,0 @@
1
- import type { Async, Static, TSchema } from "@alepha/core";
2
- import { KIND, NotImplementedError, __descriptor } from "@alepha/core";
3
- import type { UserAccountToken } from "@alepha/security";
4
- import type { CookieManager } from "@alepha/server";
5
- import type { FC } from "react";
6
- import type { RouterHookApi } from "../hooks/RouterHookApi";
7
- import {} from "../services/Router";
8
- import type { RouterRenderHelmetContext } from "../services/Router";
9
-
10
- export const pageDescriptorKey = "PAGE";
11
-
12
- export interface PageDescriptorConfigSchema {
13
- query?: TSchema;
14
- params?: TSchema;
15
- }
16
- export type TPropsDefault = any;
17
- export type TPropsParentDefault = object;
18
-
19
- export interface PageDescriptorOptions<
20
- TConfig extends PageDescriptorConfigSchema = PageDescriptorConfigSchema,
21
- TProps extends object = TPropsDefault,
22
- TPropsParent extends object = TPropsParentDefault,
23
- > {
24
- /**
25
- *
26
- */
27
- name?: string;
28
-
29
- /**
30
- *
31
- */
32
- path?: string;
33
-
34
- /**
35
- *
36
- */
37
- schema?: TConfig;
38
-
39
- /**
40
- * Function to call when the page is loaded.
41
- */
42
- resolve?: (
43
- config: PageDescriptorConfigValue<TConfig> &
44
- TPropsParent & { context: PageContext },
45
- context: PageContext,
46
- ) => Async<TProps>;
47
-
48
- /**
49
- * Component to render when the page is loaded.
50
- */
51
- component?: FC<TProps & TPropsParent>;
52
-
53
- /**
54
- * Component to render when the page is loaded. (like .component)
55
- */
56
- lazy?: () => Promise<{ default: FC<TProps & TPropsParent> }>;
57
-
58
- /**
59
- *
60
- */
61
- children?: () => Array<{ options: PageDescriptorOptions }>;
62
-
63
- /**
64
- *
65
- */
66
- parent?: { options: PageDescriptorOptions<any, TPropsParent> };
67
-
68
- /**
69
- *
70
- */
71
- helmet?:
72
- | RouterRenderHelmetContext
73
- | ((props: TProps) => RouterRenderHelmetContext);
74
-
75
- /**
76
- *
77
- */
78
- notFoundHandler?: FC<{ error: Error }>;
79
-
80
- /**
81
- *
82
- */
83
- errorHandler?: FC<{ error: Error; url: string }>;
84
- }
85
-
86
- export interface PageContext {
87
- user?: UserAccountToken;
88
- cookies?: CookieManager;
89
- }
90
-
91
- export interface PageDescriptorConfigValue<
92
- TConfig extends PageDescriptorConfigSchema = PageDescriptorConfigSchema,
93
- > {
94
- query: TConfig["query"] extends TSchema
95
- ? Static<TConfig["query"]>
96
- : Record<string, string>;
97
- params: TConfig["params"] extends TSchema
98
- ? Static<TConfig["params"]>
99
- : Record<string, string>;
100
- pathname: string;
101
- }
102
-
103
- export interface PageDescriptor<
104
- TConfig extends PageDescriptorConfigSchema = PageDescriptorConfigSchema,
105
- TProps extends object = TPropsDefault,
106
- TPropsParent extends object = TPropsParentDefault,
107
- > {
108
- [KIND]: typeof pageDescriptorKey;
109
- render: (options?: {
110
- params?: Record<string, string>;
111
- query?: Record<string, string>;
112
- }) => Promise<string>;
113
- go: () => void;
114
- createAnchorProps: (routerHook: RouterHookApi) => {
115
- href: string;
116
- onClick: () => void;
117
- };
118
- options: PageDescriptorOptions<TConfig, TProps, TPropsParent>;
119
- }
120
-
121
- export const $page = <
122
- TConfig extends PageDescriptorConfigSchema = PageDescriptorConfigSchema,
123
- TProps extends object = TPropsDefault,
124
- TPropsParent extends object = TPropsParentDefault,
125
- >(
126
- options: PageDescriptorOptions<TConfig, TProps, TPropsParent>,
127
- ): PageDescriptor<TConfig, TProps, TPropsParent> => {
128
- __descriptor(pageDescriptorKey);
129
- return {
130
- [KIND]: pageDescriptorKey,
131
- options,
132
- render: () => {
133
- throw new NotImplementedError(pageDescriptorKey);
134
- },
135
- go: () => {
136
- throw new NotImplementedError(pageDescriptorKey);
137
- },
138
- createAnchorProps: () => {
139
- throw new NotImplementedError(pageDescriptorKey);
140
- },
141
- };
142
- };
143
-
144
- $page[KIND] = pageDescriptorKey;
@@ -1,7 +0,0 @@
1
- import type { HrefLike } from "../hooks/RouterHookApi";
2
-
3
- export class RedirectionError extends Error {
4
- constructor(public readonly page: HrefLike) {
5
- super("Redirection");
6
- }
7
- }
@@ -1,154 +0,0 @@
1
- import {} from "react";
2
- import type {
3
- ReactBrowserProvider,
4
- RouterGoOptions,
5
- } from "../providers/ReactBrowserProvider";
6
- import type { AnchorProps, RouterState } from "../services/Router";
7
-
8
- export class RouterHookApi {
9
- constructor(
10
- private readonly state: RouterState,
11
- private readonly layer: {
12
- path: string;
13
- },
14
- private readonly browser?: ReactBrowserProvider,
15
- ) {}
16
-
17
- /**
18
- *
19
- */
20
- public get current(): RouterState {
21
- return this.state;
22
- }
23
-
24
- /**
25
- *
26
- */
27
- public get pathname(): string {
28
- return this.state.pathname;
29
- }
30
-
31
- /**
32
- *
33
- */
34
- public get query(): Record<string, string> {
35
- const query: Record<string, string> = {};
36
-
37
- for (const [key, value] of new URLSearchParams(
38
- this.state.search,
39
- ).entries()) {
40
- query[key] = String(value);
41
- }
42
-
43
- return query;
44
- }
45
-
46
- /**
47
- *
48
- */
49
- public async back() {
50
- this.browser?.history.back();
51
- }
52
-
53
- /**
54
- *
55
- */
56
- public async forward() {
57
- this.browser?.history.forward();
58
- }
59
-
60
- /**
61
- *
62
- * @param props
63
- */
64
- public async invalidate(props?: Record<string, any>) {
65
- await this.browser?.invalidate(props);
66
- }
67
-
68
- /**
69
- * Create a valid href for the given pathname.
70
- *
71
- * @param pathname
72
- * @param layer
73
- */
74
- public createHref(pathname: HrefLike, layer: { path: string } = this.layer) {
75
- if (typeof pathname === "object") {
76
- pathname = pathname.options.path ?? "";
77
- }
78
-
79
- return pathname.startsWith("/")
80
- ? pathname
81
- : `${layer.path}/${pathname}`.replace(/\/\/+/g, "/");
82
- }
83
-
84
- /**
85
- *
86
- * @param path
87
- * @param options
88
- */
89
- public async go(
90
- path: HrefLike,
91
- options: RouterGoOptions = {},
92
- ): Promise<void> {
93
- return await this.browser?.go(this.createHref(path, this.layer), options);
94
- }
95
-
96
- /**
97
- *
98
- * @param path
99
- */
100
- public createAnchorProps(path: string): AnchorProps {
101
- const href = this.createHref(path, this.layer);
102
- return {
103
- href,
104
- onClick: (ev: any) => {
105
- ev.stopPropagation();
106
- ev.preventDefault();
107
-
108
- this.go(path).catch(console.error);
109
- },
110
- };
111
- }
112
-
113
- /**
114
- * Set query params.
115
- *
116
- * @param record
117
- * @param options
118
- */
119
- public setQueryParams(
120
- record: Record<string, any>,
121
- options: {
122
- /**
123
- * If true, this will merge current query params with the new ones.
124
- */
125
- merge?: boolean;
126
-
127
- /**
128
- * If true, this will add a new entry to the history stack.
129
- */
130
- push?: boolean;
131
- } = {},
132
- ) {
133
- const search = new URLSearchParams(
134
- options.merge
135
- ? {
136
- ...this.query,
137
- ...record,
138
- }
139
- : {
140
- ...record,
141
- },
142
- ).toString();
143
-
144
- const state = search ? `${this.pathname}?${search}` : this.pathname;
145
-
146
- if (options.push) {
147
- window.history.pushState({}, "", state);
148
- } else {
149
- window.history.replaceState({}, "", state);
150
- }
151
- }
152
- }
153
-
154
- export type HrefLike = string | { options: { path?: string; name?: string } };
@@ -1,57 +0,0 @@
1
- import { useContext, useEffect, useMemo, useState } from "react";
2
- import { RouterContext } from "../contexts/RouterContext";
3
- import { RouterLayerContext } from "../contexts/RouterLayerContext";
4
- import type { AnchorProps } from "../services/Router";
5
- import type { HrefLike } from "./RouterHookApi";
6
- import { useRouter } from "./useRouter";
7
-
8
- export const useActive = (path: HrefLike): UseActiveHook => {
9
- const router = useRouter();
10
- const ctx = useContext(RouterContext);
11
- const layer = useContext(RouterLayerContext);
12
- if (!ctx || !layer) {
13
- throw new Error("useRouter must be used within a RouterProvider");
14
- }
15
-
16
- let name: string | undefined;
17
- if (typeof path === "object" && path.options.name) {
18
- name = path.options.name;
19
- }
20
-
21
- const [current, setCurrent] = useState(ctx.state.pathname);
22
- const href = useMemo(() => router.createHref(path, layer), [path, layer]);
23
- const [isPending, setPending] = useState(false);
24
- const isActive = current === href;
25
-
26
- useEffect(
27
- () => ctx.router.on("end", ({ pathname }) => setCurrent(pathname)),
28
- [],
29
- );
30
-
31
- return {
32
- name,
33
- isPending,
34
- isActive,
35
- anchorProps: {
36
- href,
37
- onClick: (ev: any) => {
38
- ev.stopPropagation();
39
- ev.preventDefault();
40
- if (isActive) return;
41
- if (isPending) return;
42
-
43
- setPending(true);
44
- router.go(href).then(() => {
45
- setPending(false);
46
- });
47
- },
48
- },
49
- };
50
- };
51
-
52
- export interface UseActiveHook {
53
- isActive: boolean;
54
- anchorProps: AnchorProps;
55
- isPending: boolean;
56
- name?: string;
57
- }
@@ -1,29 +0,0 @@
1
- import type { UserAccountToken } from "@alepha/security";
2
- import { useContext } from "react";
3
- import { RouterContext } from "../contexts/RouterContext";
4
- import { Auth } from "../services/Auth";
5
-
6
- export const useAuth = (): AuthHook => {
7
- const ctx = useContext(RouterContext);
8
- if (!ctx) {
9
- throw new Error("useAuth must be used within a RouterContext");
10
- }
11
-
12
- const args = ctx.args ?? {};
13
-
14
- return {
15
- user: args.user,
16
- logout: () => {
17
- ctx.alepha.get(Auth).logout();
18
- },
19
- login: (provider?: string) => {
20
- ctx.alepha.get(Auth).login();
21
- },
22
- };
23
- };
24
-
25
- export interface AuthHook {
26
- user?: UserAccountToken;
27
- logout: () => void;
28
- login: (provider?: string) => void;
29
- }
@@ -1,6 +0,0 @@
1
- import { HttpClient } from "@alepha/server";
2
- import { useInject } from "./useInject";
3
-
4
- export const useClient = (): HttpClient => {
5
- return useInject(HttpClient);
6
- };
@@ -1,12 +0,0 @@
1
- import type { Class } from "@alepha/core";
2
- import { useContext } from "react";
3
- import { RouterContext } from "../contexts/RouterContext";
4
-
5
- export const useInject = <T extends object>(clazz: Class<T>): T => {
6
- const ctx = useContext(RouterContext);
7
- if (!ctx) {
8
- throw new Error("useRouter must be used within a <RouterProvider>");
9
- }
10
-
11
- return ctx.alepha.get(clazz);
12
- };
@@ -1,59 +0,0 @@
1
- import type { Alepha, Static, TObject } from "@alepha/core";
2
- import { useContext, useEffect, useState } from "react";
3
- import { RouterContext } from "../contexts/RouterContext";
4
- import { useRouter } from "./useRouter";
5
-
6
- export interface UseQueryParamsHookOptions {
7
- format?: "base64" | "querystring";
8
- key?: string;
9
- push?: boolean;
10
- }
11
-
12
- export const useQueryParams = <T extends TObject>(
13
- schema: T,
14
- options: UseQueryParamsHookOptions = {},
15
- ): [Static<T>, (data: Static<T>) => void] => {
16
- const ctx = useContext(RouterContext);
17
- if (!ctx) {
18
- throw new Error("useQueryParams must be used within a RouterProvider");
19
- }
20
-
21
- const key = options.key ?? "q";
22
- const router = useRouter();
23
- const querystring = router.query[key];
24
-
25
- const [queryParams, setQueryParams] = useState(
26
- decode(ctx.alepha, schema, router.query[key]),
27
- );
28
-
29
- useEffect(() => {
30
- setQueryParams(decode(ctx.alepha, schema, querystring));
31
- }, [querystring]);
32
-
33
- return [
34
- queryParams,
35
- (queryParams: Static<T>) => {
36
- setQueryParams(queryParams);
37
- router.setQueryParams(
38
- { [key]: encode(ctx.alepha, schema, queryParams) },
39
- {
40
- merge: true,
41
- },
42
- );
43
- },
44
- ];
45
- };
46
-
47
- // ---------------------------------------------------------------------------------------------------------------------
48
-
49
- const encode = (alepha: Alepha, schema: TObject, data: any) => {
50
- return btoa(JSON.stringify(alepha.parse(schema, data)));
51
- };
52
-
53
- const decode = (alepha: Alepha, schema: TObject, data: any) => {
54
- try {
55
- return alepha.parse(schema, JSON.parse(atob(decodeURIComponent(data))));
56
- } catch (error) {
57
- return {};
58
- }
59
- };
@@ -1,28 +0,0 @@
1
- import { useContext, useMemo } from "react";
2
- import { RouterContext } from "../contexts/RouterContext";
3
- import { RouterLayerContext } from "../contexts/RouterLayerContext";
4
- import { ReactBrowserProvider } from "../providers/ReactBrowserProvider";
5
- import { RouterHookApi } from "./RouterHookApi";
6
-
7
- /**
8
- *
9
- */
10
- export const useRouter = (): RouterHookApi => {
11
- const ctx = useContext(RouterContext);
12
- const layer = useContext(RouterLayerContext);
13
- if (!ctx || !layer) {
14
- throw new Error("useRouter must be used within a RouterProvider");
15
- }
16
-
17
- return useMemo(
18
- () =>
19
- new RouterHookApi(
20
- ctx.state,
21
- layer,
22
- ctx.alepha.isBrowser()
23
- ? ctx.alepha.get(ReactBrowserProvider)
24
- : undefined,
25
- ),
26
- [ctx.router, layer],
27
- );
28
- };
@@ -1,43 +0,0 @@
1
- import { useContext, useEffect } from "react";
2
- import { RouterContext } from "../contexts/RouterContext";
3
- import { RouterLayerContext } from "../contexts/RouterLayerContext";
4
- import type { RouterState } from "../services/Router";
5
-
6
- export const useRouterEvents = (
7
- opts: {
8
- onBegin?: () => void;
9
- onEnd?: (it: RouterState) => void;
10
- onError?: (it: Error) => void;
11
- } = {},
12
- ) => {
13
- const ctx = useContext(RouterContext);
14
- const layer = useContext(RouterLayerContext);
15
- if (!ctx || !layer) {
16
- throw new Error("useRouter must be used within a RouterProvider");
17
- }
18
-
19
- useEffect(() => {
20
- const subs: Function[] = [];
21
- const onBegin = opts.onBegin;
22
- const onEnd = opts.onEnd;
23
- const onError = opts.onError;
24
-
25
- if (onBegin) {
26
- subs.push(ctx.router.on("begin", onBegin));
27
- }
28
-
29
- if (onEnd) {
30
- subs.push(ctx.router.on("end", onEnd));
31
- }
32
-
33
- if (onError) {
34
- subs.push(ctx.router.on("error", onError));
35
- }
36
-
37
- return () => {
38
- for (const sub of subs) {
39
- sub();
40
- }
41
- };
42
- }, []);
43
- };
@@ -1,23 +0,0 @@
1
- import { useContext, useEffect, useState } from "react";
2
- import { RouterContext } from "../contexts/RouterContext";
3
- import { RouterLayerContext } from "../contexts/RouterLayerContext";
4
- import type { RouterState } from "../services/Router";
5
-
6
- export const useRouterState = (): RouterState => {
7
- const ctx = useContext(RouterContext);
8
- const layer = useContext(RouterLayerContext);
9
- if (!ctx || !layer) {
10
- throw new Error("useRouter must be used within a RouterProvider");
11
- }
12
-
13
- const [state, setState] = useState(ctx.state);
14
- useEffect(
15
- () =>
16
- ctx.router.on("end", (it) => {
17
- setState({ ...it });
18
- }),
19
- [],
20
- );
21
-
22
- return state;
23
- };
@@ -1,21 +0,0 @@
1
- import { $inject, Alepha, autoInject } from "@alepha/core";
2
- import { $page } from "./descriptors/$page";
3
- import { PageDescriptorProvider } from "./providers/PageDescriptorProvider";
4
- import { ReactBrowserProvider } from "./providers/ReactBrowserProvider";
5
- import { Auth } from "./services/Auth";
6
-
7
- export * from "./index.shared";
8
- export * from "./providers/ReactBrowserProvider";
9
-
10
- export class ReactModule {
11
- protected readonly alepha = $inject(Alepha);
12
-
13
- constructor() {
14
- this.alepha //
15
- .with(PageDescriptorProvider)
16
- .with(ReactBrowserProvider)
17
- .with(Auth);
18
- }
19
- }
20
-
21
- autoInject($page, ReactModule);
@@ -1,28 +0,0 @@
1
- export { default as NestedView } from "./components/NestedView";
2
- export { default as Link } from "./components/Link";
3
-
4
- export * from "./contexts/RouterContext";
5
- export * from "./contexts/RouterLayerContext";
6
-
7
- export * from "./services/Auth";
8
-
9
- export * from "./descriptors/$page";
10
- export * from "./descriptors/$auth";
11
-
12
- export * from "./hooks/RouterHookApi";
13
-
14
- // --- Hooks
15
- // - core
16
- export * from "./hooks/useInject";
17
- // - http
18
- export * from "./hooks/useClient";
19
- // - router
20
- export * from "./hooks/useQueryParams";
21
- export * from "./hooks/useRouter";
22
- export * from "./hooks/useRouterEvents";
23
- export * from "./hooks/useRouterState";
24
- export * from "./hooks/useActive";
25
- // - auth
26
- export * from "./hooks/useAuth";
27
-
28
- export * from "./services/Router";