/
index.tsx
759 lines (621 loc) · 21.7 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
import React from 'react';
import { hydrateRoot, createRoot } from 'react-dom/client';
import { HelmetProvider } from 'react-helmet-async';
import UrlPattern from 'url-pattern';
import { BackendRemote } from './backend';
import axios, { Axios } from 'axios';
import _path from 'path';
import { SocketApi, SocketController, createSocket } from './socket';
import { ErrorBoundary } from "react-error-boundary";
const path = _path.posix;
function* infinite() {
let index = 0;
let timestamp = (new Date()).valueOf();
const g = () => `${timestamp}_${index}`;
while (true) {
index++;
yield g();
}
return g();
}
export const generator = infinite();
type RoleMapping = {
userId: string,
role: string
}
type Context = {
token: string
isAuthenticated: boolean,
currentUser: any,
roles: RoleMapping[]
}
const getCookies = function () {
var pairs = document.cookie.split(";");
var cookies: any = {};
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split("=");
cookies[(pair[0] + '').trim()] = unescape(pair.slice(1).join('='));
}
return cookies;
}
export class FrontendController {
static instance: FrontendController;
static getInstance() {
if (!FrontendController.instance) {
FrontendController.instance = new FrontendController();
}
return FrontendController.instance;
}
registeredComponents: any[] = [];
arkConfig: any = null;
context = {
token: null,
isAuthenticated: false,
currentUser: null
}
map: any = {};
applets: any[] = [];
client: Axios = axios.create();
socketController: SocketController = new SocketController();
subscribe(event: string, handler: any): () => void {
let id = String(generator.next().value);
if (!this.map[event]) {
this.map[event] = {};
}
this.map[event][id] = async (...args: any[]) => {
try {
if (handler) {
await Promise.resolve(handler(...args));
}
} catch (e) {
console.error(e);
}
};
return () => {
delete this.map[event][id]
}
}
async emit(event: string, ...args: any[]): Promise<void> {
if (this.map[event]) {
const handlers = Object.keys(this.map[event]).map((k) => this.map[event][k]);
await Promise.allSettled(handlers.map((h) => h && h(...args)));
}
}
async refreshContext() {
const res = await axios.post('/__backend/__context');
this.context = res.data;
this.emit('core/context/change', this.context)
}
setAuthCookie(v: any) {
const hasChanged = this?.context?.token !== v;
if (hasChanged === true) {
this.refreshContext();
}
this.context.token = v;
}
constructor() {
this.refreshContext.bind(this);
this.client.interceptors.response.use((v) => {
let authToken = getCookies();
authToken = authToken['authorization'] || null;
this.setAuthCookie(authToken);
return v;
});
/** Attempt to hydrate the state */
try {
// @ts-ignore
const ___ark_hydrated_state___ = globalThis['___ark_hydrated_state___'];
if (___ark_hydrated_state___) {
this.context = ___ark_hydrated_state___;
}
} catch (e) {
console.error(e);
}
}
}
export const backend = BackendRemote.getInstance();
export const controllerRef = FrontendController.getInstance();
// @ts-ignore
export const ControllerContext = React.createContext<FrontendController>(null);
// @ts-ignore
export const SocketContext = React.createContext<SocketApi>(null);
/* -------------------------------------------------------------------------- */
/* Core Hooks */
/* -------------------------------------------------------------------------- */
export function useLogin() {
const controller = React.useContext(ControllerContext);
const [context, setContext] = React.useState<Context>(controller.context as any);
React.useEffect(() => {
const handler = (ctx: any) => {
setContext(ctx);
}
const unsub = controller.subscribe('core/context/change', handler);
return unsub;
}, []);
const logout = React.useCallback(async () => {
return await controller.client.post('/__backend/__context/logout');
}, []);
const isCurrentUserInAnyRoles = React.useCallback((roles: string | string[]) => {
if (!Array.isArray(roles)) {
roles = [roles];
}
if (Array.isArray(context?.roles) && context?.roles.length > 0) {
return Boolean(context.roles.find((r) => roles.indexOf(r.role) > -1));
}
return false;
}, [context?.roles]);
return { current: context, logout, isCurrentUserInAnyRoles }
}
export function useAxios() {
const { controller } = useController();
return controller.client;
}
export function useController() {
const controller = React.useContext(ControllerContext);
return { controller }
}
export function useSocket() {
return React.useContext(SocketContext)
}
/* -------------------------------------------------------------------------- */
/* View */
/* -------------------------------------------------------------------------- */
interface ReactComponent { (...props: any[]): any; getInitialState?: () => any; }
export function createComponent(component: ReactComponent) {
return component;
}
export function registerView(path: string, id: string, Component: any) {
controllerRef.registeredComponents.push({
path,
Component
})
}
export function registerApplet(meta: any, Component: any) {
controllerRef.applets.push({
...meta,
Component
});
}
/* -------------------------------------------------------------------------- */
/* Route Begins */
/* -------------------------------------------------------------------------- */
type RouteApi = {
pathname: string,
match?: any,
component?: any
push: (path: string) => void
isInitialRender: boolean
getQuery: () => any
}
// @ts-ignore
const RouteProvider = React.createContext<RouteApi>(null);
const RouteMetaContext = React.createContext<any>(null);
const AppletMetaContext = React.createContext<any>(null);
export function attachRouteMeta(routeMeta: any, Comp: any) {
return (props: any) => (
<RouteMetaContext.Provider value={routeMeta}>
<Comp {...props} />
</RouteMetaContext.Provider>
)
}
export function attachAppletMeta(appletMeta: any, Comp: any) {
return (props: any) => (
<AppletMetaContext.Provider value={appletMeta}>
<Comp {...props} />
</AppletMetaContext.Provider>
)
}
export function useRouteMeta() {
return React.useContext(RouteMetaContext);
}
export function useAppletMeta() {
return React.useContext(AppletMetaContext);
}
function createRoute(defaultRoot: string, controller: FrontendController): RouteApi {
const [isInitialRender, setIsInitialRender] = React.useState(true);
const [pathname, setPathname] = React.useState(defaultRoot || globalThis?.window?.location?.pathname);
React.useEffect(() => {
window.onpopstate = () => {
setIsInitialRender(false);
setPathname(window.location.pathname);
}
}, [])
const push = React.useCallback((path: string) => {
window.history.pushState({}, '', path);
setIsInitialRender(false);
const url = new URL(path, `http://localhost`)
setPathname(url.pathname);
}, []);
const [match, component] = React.useMemo(() => {
let match: any;
let component: any;
for (const item of controller.registeredComponents) {
const pattern = new UrlPattern(item.path);
match = pattern.match(pathname);
if (match) {
component = item;
break;
}
}
return [match, component];
}, [pathname]);
const getQuery = React.useCallback(() => {
const url = new URL(window.location.href);
let r: any = {};
url.searchParams.forEach((v, k) => {
r[k] = v;
});
return r;
}, []);
return {
pathname,
match,
component,
push,
isInitialRender,
getQuery
}
}
export function useRoute(): RouteApi {
return React.useContext(RouteProvider);
}
export function useParams() {
const { pathname } = useRoute();
const routeMeta = useRouteMeta();
const appletMeta = useAppletMeta();
const { controller } = useController();
const routeInfo = React.useMemo(() => {
return getRouteInfoByPageId(routeMeta?.pageId, controller);
}, [pathname, routeMeta?.pageId]);
let url: string = React.useMemo(() => {
if (routeInfo) {
const { path } = routeInfo;
try {
return path
} catch (e) {
console.error(e);
return path;
}
}
return '';
}, [routeInfo]);
let appletUrl = React.useMemo(() => {
if (appletMeta) {
let mounts = getMountsByPageId(routeMeta?.pageId, controller);
let currentMount = mounts.find((m) => m.appletId === appletMeta?.genricPath);
return currentMount?.path || '';
}
return '';
}, [pathname, routeMeta?.pageId]);
const finalUrl = React.useMemo(() => {
return path.join(url, appletUrl);
}, [url, appletUrl]);
const params = React.useMemo(() => {
const pattern = new UrlPattern(finalUrl);
return pattern.match(pathname);
}, [finalUrl, pathname]);
return params;
}
function PageRenderer(props: any) {
const { component, isInitialRender, pathname } = useRoute();
if (!component?.Component) {
return (
<iframe style={{ width: '100vw', height: '100vh' }} src={`https://mern.ai/templates/__notfound?path=${pathname}`} />
);
}
const Component = React.useMemo(() => {
return component.Component;
}, [component.Component]);
if (isInitialRender === false) {
return (
<React.Suspense fallback={<div></div>}>
<Component {...props} />
</React.Suspense>
)
}
return (
<Component {...props} />
)
}
function getRouteInfoByPageId(pageId: string, controller: FrontendController) {
if (Array.isArray(controller?.arkConfig?.routes)) {
return controller.arkConfig.routes.find((r: any) => r.pageId === pageId);
}
return null;
}
export type LinkDisplayProps = {
pageId?: string,
appletId?: string
params?: any,
query?: any
children?: (props: { url: string }) => JSX.Element
}
export function LinkDisplay(props: LinkDisplayProps): JSX.Element {
const { params } = props;
const routeMeta = useRouteMeta();
const appletMeta = useAppletMeta();
const { controller } = useController();
const pageId = React.useMemo(() => {
return props?.pageId || routeMeta?.pageId;
}, [props.pageId, routeMeta?.pageId]);
const routeInfo = React.useMemo(() => {
return getRouteInfoByPageId(pageId, controller);
}, [pageId]);
let url: string = React.useMemo(() => {
if (routeInfo) {
const { path } = routeInfo;
try {
const pat = new UrlPattern(path);
return pat.stringify(params)
} catch (e) {
console.error(e);
return path;
}
}
return '';
}, [routeInfo, params]);
let appletUrl = React.useMemo(() => {
if (props.appletId) {
let mounts = getMountsByPageId(pageId, controller);
let mount: any = mounts.find((m) => m.appletId === props.appletId);
if (!mount) {
mount = mounts.find((m) => m.appletId === path.join(appletMeta?.featurePath, props?.appletId || ''));
}
if (mount) {
const pat = new UrlPattern(mount.path);
return pat.stringify(params);
}
}
return '';
}, [pageId, props.appletId, appletMeta?.featurePath]);
let finalUrl = React.useMemo(() => {
return path.join(url, appletUrl);
}, [url, appletUrl])
finalUrl = React.useMemo(() => {
if (props.query) {
const searchP = new URLSearchParams(props.query)
if (searchP.size > 0) {
return `${finalUrl}?${searchP.toString()}`
}
}
return finalUrl;
}, [finalUrl, props.query]);
if (finalUrl && props?.children && finalUrl !== '.') {
return props.children({ url: finalUrl })
}
return (<></>)
}
export function Link(props: { to?: string, target?: React.HTMLAttributeAnchorTarget, children?: any, className?: string }) {
const { to, target } = props;
const { push } = useRoute();
return (
<a className={props.className} target={target} href={to} onClick={(e) => {
if (e.ctrlKey || e.metaKey) {
return;
}
if (target) {
return;
}
e.preventDefault();
if (to) {
push(to);
}
}}>
{props.children}
</a>
)
}
/* -------------------------------------------------------------------------- */
/* Route Ends */
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
/* Portal */
/* -------------------------------------------------------------------------- */
export function importUI(id: string) {
return (props: any) => <Applet {...props} id={id} />
}
export function Applet(props: { id: string } & any) {
const { controller } = useController();
const { id, ...rest } = props;
const applet = React.useMemo(() => {
for (const applet of controller.applets) {
const isIdMatching = (applet?.resolvers || []).indexOf(id) > -1;
if (isIdMatching === true) {
return applet;
}
}
}, [id]);
if (!applet) {
return null;
}
return (
<React.Suspense fallback={<div></div>}>
<applet.Component {...rest} />
</React.Suspense>
)
}
export function Mount(props: { path: string }) {
const { controller } = useController();
const routeMeta = useRouteMeta();
const id = React.useMemo(() => {
if (routeMeta?.pageId) {
const mounts = getMountsByPageId(routeMeta?.pageId, controller);
const mount = mounts.find((m) => {
const pattern = new UrlPattern(m.path);
return Boolean(pattern.match(props.path));
});
if (mount) {
return mount.appletId
}
}
return null;
}, [routeMeta?.pageId, props.path]);
if (id) {
return (
<Applet id={id} />
)
}
return (
<></>
)
}
/* -------------------------------------------------------------------------- */
/* Mounts */
/* -------------------------------------------------------------------------- */
export type Mounts = {
appletId: string,
path: string,
label: string,
link: boolean
pageId: string
}
function getMountsByPageId(pageId: string, controller: FrontendController): Mounts[] {
const m = controller.applets.reduce((acc, app) => {
const matchingMounts = app.mounts.filter((m: any) => m.pageId === pageId);
acc.push(...matchingMounts.map((mount: any) => {
let pathVal = (mount?.path || app.genricPath);
if (mount?.pathPostfix) {
pathVal = path.posix.join(pathVal, mount?.pathPostfix);
}
return {
sort: 0,
...mount,
label: mount?.label || app.defaultLabel,
path: pathVal,
resolvers: app.resolvers,
appletId: app.resolvers[0]
}
}));
return acc;
}, []).sort((a: any, b: any) => {
if (a.sort > b.sort) {
return 1;
} else if (a.sort < b.sort) {
return -1;
}
return 0;
});
return m;
}
export function useMounts() {
const { controller } = useController();
const meta = useRouteMeta();
const mounts: Mounts[] = React.useMemo(() => {
if (meta?.pageId) {
return getMountsByPageId(meta?.pageId, controller);
}
return [];
}, [meta?.pageId]);
return { current: mounts }
}
/* -------------------------------------------------------------------------- */
/* Auth */
/* -------------------------------------------------------------------------- */
export function Protected(props: any) {
const { current } = useLogin();
if (current.isAuthenticated === false) {
return (
<RedirectToLoginPage />
)
}
return props.children;
}
export function RedirectToLoginPage() {
const { controller } = useController();
let authPageId = React.useMemo(() => {
if (controller?.arkConfig?.authPageId) {
return controller?.arkConfig?.authPageId;
}
return 'login';
}, [controller]);
const loginRoute = React.useMemo(() => {
if (Array.isArray(controller.arkConfig?.routes)) {
return controller.arkConfig.routes.find((r) => r.pageId === authPageId);
}
return null;
}, [authPageId, controller.arkConfig]);
React.useEffect(() => {
if (loginRoute) {
const { path } = loginRoute;
const url = new URL('http://localhost');
url.pathname = path;
url.searchParams.set('return_path', encodeURIComponent(`${global.window.location.pathname}${global.window.location.search}`));
window.location.replace(`${url.pathname}${url.search}`);
}
}, [loginRoute]);
return (
<div style={{ height: '100vh', width: '100vw', display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
{/* <h1 className='text-5xl'>401 Unauthorized. You need to be signed in to access this page.</h1> */}
</div>
)
}
export function goBackToReturnPath() {
const s = new URLSearchParams(window.location.search);
if (s.has('return_path')) {
const returnPath = decodeURIComponent(s.get('return_path'));
window.location.replace(returnPath);
}
}
function fallbackRender({ error, resetErrorBoundary }) {
return (
<div role="alert" style={{ backgroundColor: 'black', height: '100vh', width: '100vw', overflow: 'auto', padding: 16 }}>
<p style={{ color: 'white', fontSize: 24 }}>Error:</p>
<pre style={{ color: "red" }}>{error.message}</pre>
<pre style={{ color: "red" }}>{error.stack}</pre>
</div>
);
}
export function App(props: { initialPath?: any, helmetContext?: any, controller?: FrontendController }) {
const controller = React.useMemo(() => {
return props.controller || FrontendController.getInstance()
}, [props.controller]);
const route = createRoute(props?.initialPath, controller);
const socket = createSocket({ controller });
return (
<ErrorBoundary fallbackRender={fallbackRender}>
<HelmetProvider context={props?.helmetContext}>
<RouteProvider.Provider value={route}>
<ControllerContext.Provider value={controller}>
<SocketContext.Provider value={socket}>
<PageRenderer />
</SocketContext.Provider>
</ControllerContext.Provider>
</RouteProvider.Provider>
</HelmetProvider>
</ErrorBoundary>
)
}
export function startApp() {
const rootElem = document.getElementById('root');
if (rootElem) {
const shouldHydrate = (globalThis as any)?.___ark_hydrated_state___?.shouldHydrate === true;
if (shouldHydrate === true) {
hydrateRoot(rootElem, <App />);
} else {
const root = createRoot(rootElem);
root.render(<App />);
}
}
}
/* -------------------------------------------------------------------------- */
/* Config */
/* -------------------------------------------------------------------------- */
export function loadConfig(config: any) {
const properties = config?.properties || [];
return {
getValue(propertyName: string, defaultVal?: any): any {
const p = properties.find((p: any) => p?.name === propertyName);
return p?.value || defaultVal;
}
}
}
export { createUploader, createSrc, UploadButton } from './file-uploader';
export { useContent } from './content';
export { CMSLog } from './content-core';
export { uiUtils } from './ui-utils';
export async function waitInMs(timeourInMs: number) {
await new Promise<void>((r) => setTimeout(() => r(), timeourInMs));
}
export { usePromise } from './use-promise';
export { createTokenProvider, TokenExpiredError, TokenProvider } from './use-token';
export { useNotification } from './use-notification';