-
Notifications
You must be signed in to change notification settings - Fork 66.9k
Expand file tree
/
Copy pathAutomatedPageContext.tsx
More file actions
61 lines (50 loc) · 1.65 KB
/
AutomatedPageContext.tsx
File metadata and controls
61 lines (50 loc) · 1.65 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
import { createContext, useContext } from 'react'
import type { IncomingMessage } from 'http'
import type { JSX } from 'react'
import type { MiniTocItem } from '@/frame/components/context/ArticleContext'
import type { Context } from '@/types'
export type AutomatedPageContextT = {
title: string
intro: string
renderedPage: string | JSX.Element[]
miniTocItems: Array<MiniTocItem>
product?: string
permissions?: string
}
export const AutomatedPageContext = createContext<AutomatedPageContextT | null>(null)
export const useAutomatedPageContext = (): AutomatedPageContextT => {
const context = useContext(AutomatedPageContext)
if (!context) {
throw new Error(
'"useAutomatedPageContext" may only be used inside "AutomatedPageContext.Provider"',
)
}
return context
}
type AutomatedPageContextRequest = { context?: Partial<Context> } | IncomingMessage
type AutomatedPage = {
title: string
intro: string
product?: string
permissions?: string
rawPermissions?: string
}
export const getAutomatedPageContextFromRequest = (
req: AutomatedPageContextRequest,
): AutomatedPageContextT => {
const context = 'context' in req ? ((req.context as Partial<Context> | undefined) ?? {}) : {}
const page = context.page as AutomatedPage | undefined
if (!page) {
throw new Error('"getAutomatedPageContextFromRequest" requires req.context.page')
}
const renderedPage = context.renderedPage ?? ''
const miniTocItems = context.miniTocItems ?? []
return {
title: page.title,
intro: page.intro,
renderedPage,
miniTocItems,
product: page.product ?? '',
permissions: page.permissions ?? page.rawPermissions ?? '',
}
}