@alepha/react 0.5.2 → 0.6.1

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,90 +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 { FC } from "react";
5
- import type { RouterHookApi } from "../hooks/RouterHookApi";
6
-
7
- export const pageDescriptorKey = "PAGE";
8
-
9
- export interface PageDescriptorConfigSchema {
10
- query?: TSchema;
11
- params?: TSchema;
12
- }
13
- export type TPropsDefault = any;
14
- export type TPropsParentDefault = object;
15
-
16
- export interface PageDescriptorOptions<
17
- TConfig extends PageDescriptorConfigSchema = PageDescriptorConfigSchema,
18
- TProps extends object = TPropsDefault,
19
- TPropsParent extends object = TPropsParentDefault,
20
- > {
21
- parent?: { options: PageDescriptorOptions<any, TPropsParent> };
22
- name?: string;
23
- path?: string;
24
- schema?: TConfig;
25
- abstract?: boolean;
26
- resolve?: (
27
- config: PageDescriptorConfigValue<TConfig> &
28
- TPropsParent & { user?: UserAccountToken },
29
- ) => Async<TProps>;
30
- component?: FC<TProps & TPropsParent>;
31
- lazy?: () => Promise<{ default: FC<TProps & TPropsParent> }>;
32
- children?: () => Array<{ options: PageDescriptorOptions }>;
33
- notFoundHandler?: FC<{ error: Error }>;
34
- errorHandler?: FC<{ error: Error; url: string }>;
35
- }
36
-
37
- export interface PageDescriptorConfigValue<
38
- TConfig extends PageDescriptorConfigSchema = PageDescriptorConfigSchema,
39
- > {
40
- query: TConfig["query"] extends TSchema
41
- ? Static<TConfig["query"]>
42
- : Record<string, string>;
43
- params: TConfig["params"] extends TSchema
44
- ? Static<TConfig["params"]>
45
- : Record<string, string>;
46
- pathname: string;
47
- }
48
-
49
- export interface PageDescriptor<
50
- TConfig extends PageDescriptorConfigSchema = PageDescriptorConfigSchema,
51
- TProps extends object = TPropsDefault,
52
- TPropsParent extends object = TPropsParentDefault,
53
- > {
54
- [KIND]: typeof pageDescriptorKey;
55
- render: (options?: {
56
- params?: Record<string, string>;
57
- query?: Record<string, string>;
58
- }) => Promise<string>;
59
- go: () => void;
60
- createAnchorProps: (routerHook: RouterHookApi) => {
61
- href: string;
62
- onClick: () => void;
63
- };
64
- options: PageDescriptorOptions<TConfig, TProps, TPropsParent>;
65
- }
66
-
67
- export const $page = <
68
- TConfig extends PageDescriptorConfigSchema = PageDescriptorConfigSchema,
69
- TProps extends object = TPropsDefault,
70
- TPropsParent extends object = TPropsParentDefault,
71
- >(
72
- options: PageDescriptorOptions<TConfig, TProps, TPropsParent>,
73
- ): PageDescriptor<TConfig, TProps, TPropsParent> => {
74
- __descriptor(pageDescriptorKey);
75
- return {
76
- [KIND]: pageDescriptorKey,
77
- options,
78
- render: () => {
79
- throw new NotImplementedError(pageDescriptorKey);
80
- },
81
- go: () => {
82
- throw new NotImplementedError(pageDescriptorKey);
83
- },
84
- createAnchorProps: () => {
85
- throw new NotImplementedError(pageDescriptorKey);
86
- },
87
- };
88
- };
89
-
90
- $page[KIND] = pageDescriptorKey;
@@ -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,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 { ClassEntry } from "@alepha/core";
2
- import { useContext } from "react";
3
- import { RouterContext } from "../contexts/RouterContext";
4
-
5
- export const useInject = <T extends object>(classEntry: ClassEntry<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(classEntry);
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,19 +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
-
6
- export * from "./index.shared";
7
- export * from "./providers/ReactBrowserProvider";
8
-
9
- export class ReactModule {
10
- protected readonly alepha = $inject(Alepha);
11
-
12
- constructor() {
13
- this.alepha //
14
- .with(PageDescriptorProvider)
15
- .with(ReactBrowserProvider);
16
- }
17
- }
18
-
19
- autoInject($page, ReactModule);
@@ -1,17 +0,0 @@
1
- export { default as NestedView } from "./components/NestedView";
2
-
3
- export * from "./contexts/RouterContext";
4
- export * from "./contexts/RouterLayerContext";
5
-
6
- export * from "./descriptors/$page";
7
-
8
- export * from "./hooks/useActive";
9
- export * from "./hooks/useClient";
10
- export * from "./hooks/useInject";
11
- export * from "./hooks/useQueryParams";
12
- export * from "./hooks/RouterHookApi";
13
- export * from "./hooks/useRouter";
14
- export * from "./hooks/useRouterEvents";
15
- export * from "./hooks/useRouterState";
16
-
17
- export * from "./services/Router";
package/src/index.ts DELETED
@@ -1,29 +0,0 @@
1
- import { $inject, Alepha, autoInject } from "@alepha/core";
2
- import { ServerLinksProvider, ServerModule } from "@alepha/server";
3
- import { $page } from "./descriptors/$page";
4
- import { PageDescriptorProvider } from "./providers/PageDescriptorProvider";
5
- import { ReactServerProvider } from "./providers/ReactServerProvider";
6
- import { ReactSessionProvider } from "./providers/ReactSessionProvider";
7
- export { default as NestedView } from "./components/NestedView";
8
-
9
- export * from "./index.shared";
10
- export * from "./providers/PageDescriptorProvider";
11
- export * from "./providers/ReactBrowserProvider";
12
- export * from "./providers/ReactServerProvider";
13
- export * from "./providers/ReactSessionProvider";
14
- export * from "./services/Router";
15
-
16
- export class ReactModule {
17
- protected readonly alepha = $inject(Alepha);
18
-
19
- constructor() {
20
- this.alepha //
21
- .with(ServerModule)
22
- .with(ServerLinksProvider)
23
- .with(ReactServerProvider)
24
- .with(ReactSessionProvider)
25
- .with(PageDescriptorProvider);
26
- }
27
- }
28
-
29
- autoInject($page, ReactModule);
@@ -1,52 +0,0 @@
1
- import { $hook, $inject, Alepha } from "@alepha/core";
2
- import type { PageDescriptorOptions } from "../descriptors/$page";
3
- import { $page } from "../descriptors/$page";
4
- import type { PageRoute, PageRouteEntry } from "../services/Router";
5
- import { Router } from "../services/Router";
6
-
7
- export class PageDescriptorProvider {
8
- protected readonly alepha = $inject(Alepha);
9
- protected readonly router = $inject(Router);
10
-
11
- protected readonly configure = $hook({
12
- name: "configure",
13
- handler: () => {
14
- const pages = this.alepha.getDescriptorValues($page);
15
- for (const { value, key } of pages) {
16
- value.options.name ??= key;
17
-
18
- // skip children, we only want root pages
19
- if (pages.find((it) => it.value.options.children?.().includes(value))) {
20
- continue;
21
- }
22
-
23
- this.router.add(this.map(pages, value));
24
- }
25
- },
26
- });
27
-
28
- /**
29
- * Transform
30
- * @param pages
31
- * @param target
32
- * @protected
33
- */
34
- protected map(
35
- pages: Array<{ value: { options: PageDescriptorOptions } }>,
36
- target: { options: PageDescriptorOptions },
37
- ): PageRouteEntry {
38
- const children = target.options.children?.() ?? [];
39
-
40
- for (const it of pages) {
41
- if (it.value.options.parent === target) {
42
- children.push(it.value);
43
- }
44
- }
45
-
46
- return {
47
- ...target.options,
48
- parent: undefined,
49
- children: children.map((it) => this.map(pages, it)),
50
- } as PageRoute;
51
- }
52
- }