-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathLayout.tsx
More file actions
398 lines (373 loc) · 13.7 KB
/
Layout.tsx
File metadata and controls
398 lines (373 loc) · 13.7 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
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
import { useState, useEffect, ReactElement } from 'react';
import Head from 'next/head';
import { useRouter } from 'next/router';
import {
ColorMode,
Flex,
Heading,
IconsProvider,
ThemeProvider,
View
} from '@aws-amplify/ui-react';
import classNames from 'classnames';
import { defaultIcons } from '@/themes/defaultIcons';
import { defaultTheme } from '@/themes/defaultTheme';
import { gen1Theme } from '@/themes/gen1Theme';
import { Footer } from '@/components/Footer/';
import { GlobalNav, NavMenuItem } from '@/components/GlobalNav/GlobalNav';
import {
DEFAULT_PLATFORM,
PLATFORMS,
PLATFORM_DISPLAY_NAMES,
Platform
} from '@/data/platforms';
import { SpaceShip } from '@/components/SpaceShip';
import { RIGHT_NAV_LINKS } from '@/utils/globalnav';
import { LayoutProvider, LayoutHeader } from '@/components/Layout';
import { getSectionFromPath, SectionKey, SECTIONS } from '@/data/sections';
import { TableOfContents } from '@/components/TableOfContents';
import type { HeadingInterface } from '@/components/TableOfContents/TableOfContents';
import { Breadcrumbs } from '@/components/Breadcrumbs';
import { debounce } from '@/utils/debounce';
import '@docsearch/css';
import { usePathWithoutHash } from '@/utils/usePathWithoutHash';
import {
NextPrevious,
NEXT_PREVIOUS_SECTIONS
} from '@/components/NextPrevious';
import { Modal } from '@/components/Modal';
import { Gen1Banner } from '@/components/Gen1Banner';
import { CrossLink } from '@/components/CrossLink';
import { findDirectoryNode } from '@/utils/findDirectoryNode';
import { getPageSection } from '@/utils/getPageSection';
import { PinpointEOLBanner } from '@/components/PinpointEOLBanner';
import { LexV1EOLBanner } from '../LexV1EOLBanner';
import { ApiModalProvider } from '../ApiDocs/ApiModalProvider';
import { MarkdownMenu } from '@/components/MarkdownMenu';
export const Layout = ({
children,
hasTOC = true,
pageDescription,
pageTitle,
pageType = 'inner',
platform,
showBreadcrumbs = true,
showLastUpdatedDate = true,
url,
useCustomTitle = false
}: {
children: ReactElement;
hasTOC?: boolean;
pageDescription?: string;
pageTitle?: string;
pageType?: 'home' | 'inner';
platform?: Platform;
showBreadcrumbs?: boolean;
showLastUpdatedDate: boolean;
url?: string;
useCustomTitle?: boolean;
}) => {
const [menuOpen, toggleMenuOpen] = useState(false);
const [colorMode, setColorMode] = useState<ColorMode>('system');
const [tocHeadings, setTocHeadings] = useState<HeadingInterface[]>([]);
const mainId = 'pageMain';
const showTOC = hasTOC && tocHeadings.length > 0;
const router = useRouter();
const asPathWithNoHash = usePathWithoutHash();
const basePath = 'docs.amplify.aws';
const metaUrl = url ? url : basePath + asPathWithNoHash;
const pathname = router.pathname;
const isGen1 = asPathWithNoHash.split('/')[1] === 'gen1';
const isContributor = asPathWithNoHash.split('/')[1] === 'contribute';
const currentGlobalNavMenuItem = isContributor ? 'Contribute' : 'Docs';
const isHome = pageType === 'home';
// Section-based navigation state.
// Determine section from directory tree (page's actual section tag),
// fall back to sessionStorage only for ambiguous pages (tagged 'both').
const [activeSection, setActiveSection] = useState<SectionKey | undefined>(
() => {
if (isHome || asPathWithNoHash === '/') return 'quickstart';
return getSectionFromPath(asPathWithNoHash);
}
);
const handleSectionChange = (section: SectionKey) => {
setActiveSection(section);
if (typeof window !== 'undefined') {
sessionStorage.setItem('activeSection', section);
// Reset sidebar scroll position on section tab click
document.querySelector('.layout-sidebar-menu')?.scrollTo(0, 0);
}
};
const { section: pageSection, featureRoute } = getPageSection(pathname);
useEffect(() => {
// Homepage shows quickstart sidebar items
if (isHome || asPathWithNoHash === '/') {
setActiveSection('quickstart');
return;
}
if (pageSection) {
setActiveSection(pageSection);
} else if (typeof window !== 'undefined') {
const stored = sessionStorage.getItem('activeSection');
if (stored && stored in SECTIONS) {
setActiveSection(stored as SectionKey);
} else {
const detected = getSectionFromPath(asPathWithNoHash);
if (detected) setActiveSection(detected);
}
}
}, [asPathWithNoHash, pathname, pageSection, isHome]);
// Derive CrossLink props for the current page
const crossLinkProps = (() => {
if (isGen1 || !pageSection) return null;
// Don't show CrossLink on landing/overview pages
if (pathname.endsWith('/frontend')) return null;
if (pathname.endsWith('/build-a-backend')) return null;
// Skip feature root overviews (e.g., /build-a-backend/auth, /frontend/auth)
if (/\/\[platform\]\/(build-a-backend|frontend)\/[^/]+$/.test(pathname)) {
const node = findDirectoryNode(pathname);
if (node?.children && node.children.length > 0) return null;
}
if (pageSection === 'backend') {
return {
text: 'Looking for how to use this in your app?',
label: 'See Frontend Libraries',
href: featureRoute || '/[platform]/frontend/',
targetSection: 'frontend'
};
}
if (pageSection === 'frontend') {
return {
text: 'Need to configure your backend?',
label: 'See Build a Backend',
href: featureRoute || '/[platform]/build-a-backend/',
targetSection: 'backend'
};
}
return null;
})();
const handleColorModeChange = (mode: ColorMode) => {
setColorMode(mode);
if (mode !== 'system') {
localStorage.setItem('colorMode', mode);
} else {
localStorage.removeItem('colorMode');
}
};
const isOverview =
children?.props?.childPageNodes?.length != 'undefined' &&
children?.props?.childPageNodes?.length > 0;
const showNextPrev = NEXT_PREVIOUS_SECTIONS.some(
(section) =>
pathname.includes(section) &&
!asPathWithNoHash.endsWith(section) &&
!isOverview
);
// For 404 pages, we need to check what platform the user was visiting from so that we can
// show them the correct platform. This is because 404 pages do not have the platform in router.query.platform.
// For gen1 routes, [platform] is in index 2
const asPathPlatform = isGen1
? (asPathWithNoHash.split('/')[2] as Platform)
: (asPathWithNoHash.split('/')[1] as Platform);
// Check query parameter as fallback for platform-independent pages
const queryPlatform = router.query.platform as Platform;
const currentPlatform = platform
? platform
: PLATFORMS.includes(asPathPlatform)
? asPathPlatform
: PLATFORMS.includes(queryPlatform) // If platform is included as query parameter, attempt to use
? queryPlatform
: DEFAULT_PLATFORM;
const title = [
pageTitle,
platform ? PLATFORM_DISPLAY_NAMES[platform] : null,
isGen1
? 'AWS Amplify Gen 1 Documentation'
: 'AWS Amplify Gen 2 Documentation'
]
.filter((s) => s !== '' && s !== null)
.join(' - ');
const description = `${pageDescription} AWS Amplify Documentation`;
const handleScroll = debounce((e) => {
const bodyScroll = e.target.documentElement.scrollTop;
if (bodyScroll > 20) {
document.body.classList.add('scrolled');
} else if (document.body.classList.contains('scrolled')) {
document.body.classList.remove('scrolled');
}
}, 20);
useEffect(() => {
const headings: HeadingInterface[] = [];
const defaultHeadings = '.main > h2, .main > h3';
const cliCommandHeadings =
'.commands-list__command > h2, .commands-list__command > .commands-list__command__subcommands > h3';
const refHeadings = '.reference-page h2, .reference-page h3';
const headingSelectors = [defaultHeadings, cliCommandHeadings, refHeadings];
const pageHeadings = document.querySelectorAll(headingSelectors.join(', '));
pageHeadings.forEach((node) => {
const { innerText, id, localName } = node as HTMLElement;
if (innerText && id && localName == 'h2') {
headings.push({
linkText: innerText,
hash: id,
level: localName,
subheadings: []
});
} else if (innerText && id && localName == 'h3') {
headings[headings.length - 1].subheadings.push({
linkText: innerText,
hash: id,
level: localName
});
}
});
setTocHeadings(headings);
}, [children, pageType]);
useEffect(() => {
if (isHome) {
document.addEventListener('scroll', handleScroll);
return () => {
document.removeEventListener('scroll', handleScroll);
};
}
});
useEffect(() => {
const colorModePreference = localStorage.getItem('colorMode') as ColorMode;
if (colorModePreference) {
setColorMode(colorModePreference);
}
}, []);
return (
<>
<Head>
<title>{`${title}`}</title>
<meta property="og:title" content={title} key="og:title" />
<meta name="description" content={description} />
<meta
property="og:description"
content={description}
key="og:description"
/>
<meta property="og:url" content={metaUrl} key="og:url" />
<meta
property="og:image"
content={`https://docs.amplify.aws/assets/${
isGen1 ? 'classic' : 'gen2'
}-og.png`}
key="og:image"
/>
<meta property="description" content={description} key="description" />
<meta property="twitter:card" content="summary" key="twitter:card" />
<meta property="twitter:title" content={title} key="twitter:title" />
<meta
property="twitter:description"
content={description}
key="twitter:description"
/>
<meta
property="twitter:image"
content={`https://docs.amplify.aws/assets/${
isGen1 ? 'classic' : 'gen2'
}-og.png`}
key="twitter:image"
/>
</Head>
<LayoutProvider
value={{
colorMode,
menuOpen,
toggleMenuOpen,
handleColorModeChange
}}
>
<ThemeProvider
theme={isGen1 ? gen1Theme : defaultTheme}
colorMode={colorMode}
>
<IconsProvider icons={defaultIcons}>
<ApiModalProvider>
<Modal isGen1={isGen1} />
<View
className={classNames(
'layout-wrapper',
`layout-wrapper--${pageType}`,
{
'spaceship-layout': isHome,
'spaceship-layout--gen1': isHome && isGen1
}
)}
>
{isHome ? <SpaceShip /> : null}
<GlobalNav
rightLinks={RIGHT_NAV_LINKS as NavMenuItem[]}
currentSite={currentGlobalNavMenuItem}
isGen1={isGen1}
mainId={mainId}
activeSection={activeSection}
onSectionChange={handleSectionChange}
currentPlatform={currentPlatform}
/>
<LayoutHeader
showTOC={showTOC}
isGen1={isGen1}
currentPlatform={currentPlatform}
pageType={pageType}
showLastUpdatedDate={showLastUpdatedDate}
activeSection={activeSection}
onSectionChange={handleSectionChange}
></LayoutHeader>
<View key={asPathWithNoHash} className="layout-main">
<Flex
id={mainId}
as="main"
tabIndex={-1}
aria-label="Main content"
className={`main${showTOC ? ' main--toc' : ''}`}
>
{showBreadcrumbs ? (
<Breadcrumbs
route={pathname}
platform={currentPlatform}
/>
) : null}
{isGen1 && <Gen1Banner currentPlatform={currentPlatform} />}
{crossLinkProps && <CrossLink {...crossLinkProps} />}
{useCustomTitle ? null : (
<Flex
justifyContent="space-between"
alignItems="flex-start"
wrap="nowrap"
>
<Heading level={1}>{pageTitle}</Heading>
<MarkdownMenu
route={asPathWithNoHash}
isGen1={isGen1}
isHome={isHome}
isOverview={isOverview}
/>
</Flex>
)}
{(asPathWithNoHash.includes('/push-notifications/') ||
asPathWithNoHash.includes('/analytics/') ||
asPathWithNoHash.includes('/in-app-messaging/')) &&
!asPathWithNoHash.includes('/kinesis') &&
!asPathWithNoHash.includes('/firehose') && (
<PinpointEOLBanner />
)}
{asPathWithNoHash.includes('/interactions/') && (
<LexV1EOLBanner />
)}
{children}
{showNextPrev && <NextPrevious />}
</Flex>
{showTOC ? <TableOfContents headers={tocHeadings} /> : null}
</View>
<Footer hasTOC={showTOC} />
</View>
</ApiModalProvider>
</IconsProvider>
</ThemeProvider>
</LayoutProvider>
</>
);
};