-
Notifications
You must be signed in to change notification settings - Fork 259
Expand file tree
/
Copy pathStoplightProject.tsx
More file actions
282 lines (252 loc) · 8 KB
/
Copy pathStoplightProject.tsx
File metadata and controls
282 lines (252 loc) · 8 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
import {
type CustomLinkComponent,
findFirstNode,
ReactRouterMarkdownLink,
RouterTypeContext,
RoutingProps,
ScrollToHashElement,
SidebarLayout,
useRouter,
withStyles,
} from '@stoplight/elements-core';
import * as React from 'react';
import {
Link,
Navigate,
Outlet,
Route,
Routes,
useInRouterContext,
useNavigate,
useOutletContext,
useParams,
} from 'react-router-dom';
import { BranchSelector } from '../components/BranchSelector';
import { DevPortalProvider } from '../components/DevPortalProvider';
import { Forbidden } from '../components/Forbidden';
import { Loading } from '../components/Loading';
import { NodeContent } from '../components/NodeContent';
import { NotFound } from '../components/NotFound';
import { TableOfContents } from '../components/TableOfContents';
import { UpgradeToStarter } from '../components/UpgradeToStarter';
import { ResponseError } from '../handlers/getNodeContent';
import { useGetBranches } from '../hooks/useGetBranches';
import { useGetNodeContent } from '../hooks/useGetNodeContent';
import { useGetTableOfContents } from '../hooks/useGetTableOfContents';
export interface StoplightProjectProps extends RoutingProps {
/**
* The ID of the Stoplight Project.
* @example "d2s6NDE1NTU"
*/
projectId: string;
/**
* If your company runs an on-premise deployment of Stoplight,
* set this prop to point the StoplightProject component at the URL of that instance.
*/
platformUrl?: string;
/**
* Allows to hide TryIt component
*/
hideTryIt?: boolean;
/**
* Allows to hide mocking button
*/
hideMocking?: boolean;
/**
* Allows to hide export button
* @default false
*/
hideExport?: boolean;
/**
* Allows to the server information
* @default false
*/
hideServerInfo?: boolean;
/**
* Allows to hide the security schemes
* @default false
*/
hideSecurityInfo?: boolean;
/**
* If set to true, all table of contents panels will be collapsed.
* @default false
*/
collapseTableOfContents?: boolean;
/**
* Fetch credentials policy for TryIt component
* For more information: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
* @default "omit"
*/
tryItCredentialsPolicy?: 'omit' | 'include' | 'same-origin';
/**
* URL of a CORS proxy that will be used to send requests in TryIt.
* Provided url will be prepended to an URL of an actual request.
* @default false
*/
tryItCorsProxy?: string;
}
const StoplightProjectImpl: React.FC<StoplightProjectProps> = ({ projectId, collapseTableOfContents = false }) => {
const { branchSlug: encodedBranchSlug = '', '*': nodeSlug = '' } = useParams<{
branchSlug?: string;
'*': string;
}>();
const branchSlug = decodeURIComponent(encodedBranchSlug);
const navigate = useNavigate();
const { data: tableOfContents, isFetched: isTocFetched } = useGetTableOfContents({ projectId, branchSlug });
const { data: branches } = useGetBranches({ projectId });
const {
data: node,
isLoading: isLoadingNode,
isError,
error: nodeError,
} = useGetNodeContent({
nodeSlug: nodeSlug ?? '',
projectId,
branchSlug,
});
const container = React.useRef<HTMLDivElement>(null);
// Create a custom Link component that preserves the branch path
const BranchAwareLink = React.useMemo(() => {
return React.forwardRef<HTMLAnchorElement, React.ComponentProps<typeof Link>>((props, ref) => {
const { to, ...rest } = props;
// If we're on a branch, prefix all relative links with the branch path
// Only modify relative paths (not starting with /, #, http://, https://, or .)
const shouldPrefixBranch = branchSlug && typeof to === 'string' && to !== '.' && !/^(\/|#|https?:\/\/)/.test(to);
const adjustedTo = shouldPrefixBranch ? `branches/${encodeURIComponent(branchSlug)}/${to}` : to;
return <Link ref={ref} to={adjustedTo} {...rest} />;
});
}, [branchSlug]);
if (!nodeSlug && isTocFetched && tableOfContents?.items) {
const firstNode = findFirstNode(tableOfContents.items);
if (firstNode) {
return <Navigate to={branchSlug ? `branches/${branchSlug}/${firstNode.slug}` : `${firstNode.slug}`} replace />;
}
}
const handleTocClick = () => {
if (container.current) {
container.current.scrollIntoView();
}
};
return (
<SidebarLayout
ref={container}
sidebar={
<>
{branches && branches.items.length > 1 ? (
<BranchSelector
branchSlug={branchSlug}
branches={branches.items}
onChange={branch => {
const encodedBranchSlug = encodeURIComponent(branch.slug);
navigate(branch.is_default ? `${nodeSlug}` : `branches/${encodedBranchSlug}/${nodeSlug}`);
}}
/>
) : null}
{tableOfContents ? (
<TableOfContents
activeId={node?.id || nodeSlug?.split('-')[0] || ''}
tableOfContents={tableOfContents}
Link={BranchAwareLink as CustomLinkComponent}
collapseTableOfContents={collapseTableOfContents}
onLinkClick={handleTocClick}
/>
) : null}
</>
}
>
<Outlet context={[isLoadingNode, isTocFetched, isError, nodeError, node]} />
</SidebarLayout>
);
};
const ProjectNode: React.FC<StoplightProjectProps> = ({
hideTryIt,
hideSecurityInfo,
hideServerInfo,
hideMocking,
hideExport,
tryItCredentialsPolicy,
tryItCorsProxy,
}) => {
const { branchSlug: encodedBranchSlug = '', '*': nodeSlug = '' } = useParams<{ branchSlug?: string; '*': string }>();
const branchSlug = decodeURIComponent(encodedBranchSlug);
const [isLoadingNode, isTocFetched, isError, nodeError, node] = useOutletContext<any>();
if (isLoadingNode || !isTocFetched) {
return <Loading />;
}
if (isError) {
if (nodeError instanceof ResponseError) {
if (nodeError.code === 402) {
return <UpgradeToStarter />;
} else if (nodeError.code === 403) {
return <Forbidden />;
} else {
return <NotFound />;
}
} else {
return <NotFound />;
}
}
if (!node) {
return <NotFound />;
}
if (node?.slug && nodeSlug !== node.slug) {
// Handle redirect to node's slug
return <Navigate to={branchSlug ? `/branches/${branchSlug}/${node.slug}` : `/${node.slug}`} replace />;
}
return (
<>
<ScrollToHashElement />
<NodeContent
node={node}
Link={ReactRouterMarkdownLink}
hideTryIt={hideTryIt}
hideMocking={hideMocking}
hideExport={hideExport}
hideSecurityInfo={hideSecurityInfo}
hideServerInfo={hideServerInfo}
tryItCredentialsPolicy={tryItCredentialsPolicy}
tryItCorsProxy={tryItCorsProxy}
/>
</>
);
};
const StoplightProjectRouter = ({
platformUrl,
basePath = '/',
staticRouterPath = '',
router = 'hash',
...props
}: StoplightProjectProps) => {
const { Router, routerProps } = useRouter(router, basePath, staticRouterPath);
const outerRouter = useInRouterContext();
const InternalRoutes = () => (
<Routes>
<Route path="/" element={<StoplightProjectImpl {...props} />}>
<Route path="/branches/:branchSlug/*" element={<ProjectNode {...props} />} />
<Route path="/*" element={<ProjectNode {...props} />} />
</Route>
</Routes>
);
if (!outerRouter) {
return (
<DevPortalProvider platformUrl={platformUrl}>
<RouterTypeContext.Provider value={router}>
<Router {...routerProps} key={basePath}>
<InternalRoutes />
</Router>
</RouterTypeContext.Provider>
</DevPortalProvider>
);
}
return (
<DevPortalProvider platformUrl={platformUrl}>
<RouterTypeContext.Provider value={router}>
<InternalRoutes />
</RouterTypeContext.Provider>
</DevPortalProvider>
);
};
/**
* The StoplightProject component displays a traditional documentation UI for an existing Stoplight Project.
*/
export const StoplightProject = withStyles(StoplightProjectRouter);