-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathsection.tsx
More file actions
287 lines (263 loc) · 9.03 KB
/
Copy pathsection.tsx
File metadata and controls
287 lines (263 loc) · 9.03 KB
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
/** @jsxRuntime automatic */
/** @jsxImportSource preact */
import type { Context as PreactContext, JSX } from "preact";
import {
Component,
type ComponentChildren,
type ComponentType,
createContext,
} from "preact";
import { useContext } from "preact/hooks";
import type { HttpContext } from "../blocks/handler.ts";
import type { RequestState } from "../blocks/utils.tsx";
import { Context } from "../deco.ts";
import { type DeepPartial, Murmurhash3 } from "../deps.ts";
import type { ComponentFunc, ComponentMetadata } from "../engine/block.ts";
import type { FieldResolver } from "../engine/core/resolver.ts";
import { logger } from "../observability/otel/config.ts";
import { useFramework } from "../runtime/handler.tsx";
import { type Device, deviceOf } from "../utils/userAgent.ts";
export interface SectionContext extends HttpContext<RequestState> {
renderSalt?: string;
device: Device;
deploymentId?: string;
// deno-lint-ignore no-explicit-any
FallbackWrapper: ComponentType<any>;
}
/**
* Preact context for storing section context.
*/
export const SectionContext: PreactContext<SectionContext | undefined> =
createContext<SectionContext | undefined>(
undefined,
);
// Murmurhash3 was chosen because it is fast
const hasher = new Murmurhash3(); // This object cannot be shared across executions when a `await` keyword is used (which is not the case here).
export const getSectionID = (resolveChain: FieldResolver[]) => {
for (const { type, value } of resolveChain) {
hasher.hash(type);
hasher.hash(`${value}`);
}
const id = `${hasher.result()}`;
hasher.reset();
return id;
};
const isPreview = ([head]: FieldResolver[]) =>
head?.type === "resolver" && head?.value === "preview";
interface BoundaryProps {
error: ComponentFunc<{ error: Error }>;
loading: ComponentFunc;
component: string;
url?: URL;
blockId: string;
resolverId: string | number;
}
interface BoundaryState {
error: Promise<Error> | Error | null;
}
export class ErrorBoundary extends Component<BoundaryProps, BoundaryState> {
override state = { error: null };
static override getDerivedStateFromError(error: Error) {
return { error };
}
render() {
const error = this.state.error as Error | null;
const { loading: Loading, error: Error, children } = this.props;
const mode = error?.name === "AbortError"
? "loading"
: error
? "error"
: "children";
if (mode === "error") {
const msg =
`rendering: ${this.props.component} at ${this.props.url} with resolverId ${this.props.resolverId} ${
(error as Error)?.stack
}`;
logger.error(msg, {
host: this.props.url?.host,
pathname: this.props.url?.pathname,
search: this.props.url?.search,
component: this.props.blockId,
resolverId: this.props.resolverId,
});
console.error(msg, {
host: this.props.url?.host,
pathname: this.props.url?.pathname,
search: this.props.url?.search,
component: this.props.blockId,
resolverId: this.props.resolverId,
});
}
if (mode === "loading") {
return <Loading />;
}
if (mode === "error") {
return <Error error={error!} />;
}
return <>{children}</>;
}
}
export interface Framework {
name: string;
Head?: (headProps: { children: ComponentChildren }) => null;
Wrapper: ComponentType<
{ id: string; partialMode?: "replace" | "append" | "prepend" }
>;
ErrorFallback: ComponentType<{
id: string;
name: string;
debugEnabled?: boolean;
isDeploy: boolean;
error: Error;
}>;
LoadingFallback: ComponentType<
{ id: string; props?: Record<string, unknown> }
>;
}
export const alwaysThrow =
(err: unknown): ComponentFunc => (_props: unknown) => {
throw err;
};
const MAX_RENDER_COUNT = 5_00; // for saved sections this number should mark a restart.
export function withSection<TProps, TLoaderProps = TProps>(
resolver: string,
ComponentFunc: ComponentFunc,
LoadingFallback?: ComponentType<DeepPartial<TLoaderProps>>,
ErrorFallback?: ComponentType<{ error?: Error }>,
loaderProps?: TLoaderProps,
): (
props: TProps,
ctx: HttpContext<
RequestState & {
renderSalt?: string;
partialMode?: "replace" | "prepend" | "append";
}
>,
) => {
LoadingFallback?: (() => JSX.Element) | undefined;
props: TProps;
Component: (props: TProps) => JSX.Element;
metadata: ComponentMetadata;
} {
return ((
props: TProps,
ctx: HttpContext<
RequestState & {
renderSalt?: string;
partialMode?: "replace" | "prepend" | "append";
}
>,
) => {
let renderCount = 0;
const idPrefix = getSectionID(ctx.resolveChain);
const debugEnabled = ctx.context?.state?.debugEnabled;
const renderSaltFromState = ctx.context?.state?.renderSalt;
// TODO @gimenes This is a fresh thing only. We need to remove it on other framework bindings
const partialMode = ctx?.context?.state?.partialMode ||
"replace";
const metadata = {
resolveChain: ctx.resolveChain,
component: ctx.resolveChain.findLast((chain) => chain.type === "resolver")
?.value?.toString()!,
};
let device: Device | null = null;
return {
props,
Component: (props: TProps) => {
const { isDeploy, deploymentId } = Context.active();
// if parent salt is not defined it means that we are at the root level, meaning that we are the first partial in the rendering tree.
const { renderSalt: parentRenderSalt } = useContext(SectionContext) ??
{};
const binding = useFramework();
// if this is the case, so we can use the renderSaltFromState - which means that we are in a partial rendering phase
const renderSalt = parentRenderSalt === undefined
? renderSaltFromState ?? `${renderCount}`
: `${parentRenderSalt ?? ""}${renderCount}`; // the render salt is used to prevent duplicate ids in the same page, it starts with parent renderSalt and appends how many times this function is called.
const id = `${idPrefix}-${renderSalt}`; // all children of the same parent will have the same renderSalt, but different renderCount
renderCount = ++renderCount % MAX_RENDER_COUNT;
return (
<SectionContext.Provider
value={{
...ctx,
deploymentId,
renderSalt,
FallbackWrapper: ({ children, ...props }) => (
<binding.LoadingFallback id={id} {...props}>
{children}
</binding.LoadingFallback>
),
get device() {
return device ??= deviceOf(ctx.request);
},
}}
>
<binding.Wrapper id={id} partialMode={partialMode}>
<section
id={id}
data-manifest-key={resolver}
data-resolve-chain={isPreview(ctx.resolveChain)
? JSON.stringify(ctx.resolveChain)
: undefined}
>
<ErrorBoundary
component={resolver}
url={ctx.context?.state?.url}
blockId={resolver}
resolverId={ctx.resolverId}
loading={() => (
<binding.LoadingFallback id={id}>
{LoadingFallback
? (
// @ts-ignore difficult typing this
<LoadingFallback
{...new Proxy<Partial<TProps>>(props, {
get: (value: Partial<TProps>, prop) => {
try {
return Reflect.get(value, prop);
} catch (_) {
return undefined;
}
},
})}
/>
)
: <></>}
</binding.LoadingFallback>
)}
error={({ error }) => (
ErrorFallback
? <ErrorFallback error={error} />
: (
<binding.ErrorFallback
id={id}
name={resolver}
error={error}
isDeploy={isDeploy}
debugEnabled={debugEnabled}
/>
)
)}
>
<ComponentFunc {...props} />
</ErrorBoundary>
</section>
</binding.Wrapper>
</SectionContext.Provider>
);
},
metadata,
...LoadingFallback
? {
LoadingFallback: () => {
return (
// @ts-ignore: could not it type well
<LoadingFallback
{...(loaderProps ?? props) as DeepPartial<TLoaderProps>}
/>
);
},
}
: {},
};
});
}