-
Notifications
You must be signed in to change notification settings - Fork 0
/
suspense.ts
71 lines (68 loc) · 1.96 KB
/
suspense.ts
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
import { Observable, combineLatest, distinctUntilChanged, map } from 'rxjs'
import {
Component,
ComponentDescription,
ContextComponent,
FragmentDescription,
} from './component.js'
import { WiringContext } from './wiring-context.js'
import { wire } from './wiring.js'
/**
* Properties supported by the `<Suspense>` pseudo-component
*/
export interface SuspenseProps {
/**
* Suspend children bindings when true.
*/
when: Observable<boolean>
/**
* Show an optional component instead when suspended.
*/
suspenseView?: Component
}
/**
* Suspend the bindings in children when a observable flag has been raised.
*
* @param _props Suspense Props
*/
export const Suspense: ContextComponent<SuspenseProps> = () => {
throw new Error('Suspense is a custom-wired component')
}
export function wireSuspense(
description: ComponentDescription,
context: WiringContext,
document = globalThis.document,
): Observable<Element> {
context.isStaticComponent = false
context.isStaticTree = false
const props = description.properties as unknown as SuspenseProps
const suspense = context.suspense
? combineLatest([props.when, context.suspense]).pipe(
map(([a, b]) => a || b),
)
: props.when
const mainComponentFragment: FragmentDescription = {
type: 'fragment',
attributes: {},
children: description.children,
childrenBind: description.childrenBind,
childrenBindMode: description.childrenBindMode,
}
const mainComponent = () => mainComponentFragment
const mainContext = { ...context, suspense }
const main = wire(mainComponent, mainContext, undefined, document)
if (props.suspenseView) {
const suspenseView = wire(
props.suspenseView,
{ ...context },
undefined,
document,
)
return combineLatest([props.when, main, suspenseView]).pipe(
map(([suspend, main, suspenseView]) => (suspend ? suspenseView : main)),
distinctUntilChanged(),
)
} else {
return main
}
}