/
app.js
749 lines (675 loc) · 24.2 KB
/
app.js
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
import React, {
useState,
useEffect,
Fragment,
useRef,
createContext,
useCallback,
} from "react"
import { Router, Link, Match, navigate } from "@reach/router"
import { Helmet } from "react-helmet"
import { ReactComponent as LogoAndName } from "../assets/images/logo-and-name.svg"
import { ReactComponent as Logo } from "../assets/images/logo.svg"
import { ReactComponent as Github } from "../assets/images/github.svg"
import { ReactComponent as Twitter } from "../assets/images/twitter.svg"
import { ReactComponent as Discord } from "../assets/images/discord.svg"
import { Close, Menu } from "../components/icons"
import { ThemeProvider } from "../contexts/theme"
import { RouterProvider } from "../contexts/router"
import { useRouter } from "../hooks/use-router"
import { useTheme } from "../hooks/use-theme"
import SEO from "../components/seo"
import SignupForm from "../components/signup-form"
import ErrorBoundary from "../components/error-boundary"
import NotFound from "./not-found"
import { sidebarWidth } from "../components/three-column-layout/desktop-nav"
import "docsearch.js/dist/cdn/docsearch.min.css"
import "@reach/dialog/styles.css"
import { DialogOverlay, DialogContent } from "@reach/dialog"
import useKeyboardShortcut from "../hooks/use-keyboard-shortcut"
import { createGlobalStyle } from "styled-components"
import "focus-visible/dist/focus-visible.min.js"
import { createClient, Provider as UrqlProvider } from "urql"
// Glob import all components in the route directory
const routeComponentsMap = {}
function importAll(r) {
r.keys().forEach((key) => {
let keyWithoutExtension = key.substr(0, key.lastIndexOf(".")) || key
routeComponentsMap[keyWithoutExtension] = r(key)
})
}
importAll(require.context("./", true, /\.(js|jsx|mdx|tx|tsx)$/))
const themeClasses = {
light: {
active: "text-gray-900",
inactive: "text-gray-600 hover:text-gray-900",
divider: "border-gray-300",
},
dark: {
active: "text-gray-100",
inactive: "text-gray-500 hover:text-gray-100",
divider: "border-gray-700",
},
}
const client = createClient({
url: "https://miragejs-site-backend.herokuapp.com/v1/graphql",
})
export const CarbonAdContext = createContext()
function CarbonAdProvider({ children }) {
let [queue, setQueue] = useState([])
const register = useCallback((ref) => {
setQueue((targets) => [...targets, ref])
}, [])
const unregister = useCallback((ref) => {
// Remove this ref from the queue
setQueue((targets) => targets.filter((target) => target !== ref))
// If this ref currently contains the ad, put it back
let root = document.getElementById("carbonads-root")
let container = document.getElementById("carbonads-container")
if (ref.current.contains(container)) {
root.appendChild(container)
// If carbonads has finished loading by the time we put it back, we can refresh the ad
let carbonads = document.getElementById("carbonads")
if (carbonads) {
container.innerHTML = ""
loadCarbonAd()
}
}
}, [])
useEffect(() => {
let root = document.getElementById("carbonads-root")
let container = document.getElementById("carbonads-container")
let containerIsInRoot = root.contains(container)
let bestTarget = queue.find((target) => target.current !== null)
if (containerIsInRoot && bestTarget) {
console.log("moving ad")
bestTarget.current.appendChild(container)
}
}, [queue])
return (
<CarbonAdContext.Provider value={{ register, unregister }}>
{children}
</CarbonAdContext.Provider>
)
}
export default function (props) {
return (
<CarbonAdProvider>
<RouterProvider {...props}>
<ThemeProvider {...props}>
<UrqlProvider value={client}>
<AppInner {...props} />
</UrqlProvider>
</ThemeProvider>
</RouterProvider>
</CarbonAdProvider>
)
}
function loadCarbonAd() {
const script = document.createElement("script")
script.src =
"//cdn.carbonads.com/carbon.js?serve=CE7D42QY&placement=miragejscom"
script.id = "_carbonads_js"
document.getElementById("carbonads-container").appendChild(script)
}
function AppInner(props) {
let { theme } = useTheme()
let router = useRouter()
// activePage is not set for /api routes, once we fix this we should be able
// to remove this conditional logic.
let showHeaderNav = true // default
if (router.activePage && router.activePage.meta.showHeaderNav !== undefined) {
showHeaderNav = router.activePage.meta.showHeaderNav
}
let title
if (router.activePage && router.activePage.label) {
title = router.activePage.label
}
let carbonAdPlaceholder = useRef()
useEffect(() => {
loadCarbonAd(carbonAdPlaceholder.current)
}, [])
return (
<div className="relative z-0">
<Helmet>
<html className={`${theme === "dark" ? "bg-gray-1000" : "bg-white"}`} />
</Helmet>
<SEO title={title} />
<div className="flex flex-col min-h-screen antialiased leading-normal text-gray-700 font-body">
<Header showHeaderNav={showHeaderNav} />
<main className="flex flex-col flex-1">
<ErrorBoundary>
<Outlet />
</ErrorBoundary>
</main>
<Footer />
</div>
<div ref={carbonAdPlaceholder} className="hidden" id="carbonads-root">
<div id="carbonads-container"></div>
</div>
</div>
)
}
function Header({ showHeaderNav }) {
const { theme } = useTheme()
const [isShowingMobileNav, setIsShowingMobileNav] = useState(false)
const [isShowingSearch, setIsShowingSearch] = useState(false)
const router = useRouter()
useKeyboardShortcut("/", () => setIsShowingSearch(true))
function handleSearchSelect(productionAlgoliaUrl) {
setIsShowingSearch(false)
let url = new URL(productionAlgoliaUrl)
navigate(`${url.pathname}${url.hash}`)
}
let fullWidthHeader = router.activePage?.meta?.fullWidthHeader
let shouldShowDivider = theme === "light" && !fullWidthHeader
return (
<div
className={`z-50 ${
theme === "dark"
? "relative bg-gray-1000"
: "bg-white shadow fixed top-0 inset-x-0"
}`}
>
<div className="md:px-6">
<div className={fullWidthHeader ? null : "max-w-6xl mx-auto"}>
<header
className={`
${isShowingMobileNav && theme === "dark" ? "bg-gray-900" : ""}
`}
>
<div
className={`flex items-center ${
theme === "dark" ? "h-24" : "h-16"
}`}
>
<div
className={`flex items-center ${
shouldShowDivider ? "lg:border-r lg:border-gray-200" : ""
}`}
css={`
@media (min-width: 1024px) {
width: ${shouldShowDivider ? `${sidebarWidth}px` : "auto"};
}
`}
>
<Link
to="/"
className="px-5 md:px-0 focus:outline-none focus-visible:shadow-outline"
onClick={() => setIsShowingMobileNav(false)}
>
<LogoAndName
className={`
${
theme === "dark"
? "w-24 md:w-28 lg:w-34 py-3 text-gray-100"
: "w-24 md:w-28 text-gray-900"
}
`}
/>
</Link>
</div>
{/* Mobile nav button */}
{showHeaderNav ? (
<div className="ml-auto md:hidden">
<button
onClick={() => setIsShowingMobileNav(!isShowingMobileNav)}
className={`flex px-5 py-3 2xl:py-2 items-center focus:outline-none ${themeClasses[theme]["inactive"]} lg:hidden `}
>
{isShowingMobileNav ? (
<Close className="w-4 h-4" />
) : (
<Menu className="w-4 h-4" />
)}
</button>
</div>
) : null}
{/* Desktop nav */}
{showHeaderNav ? (
<>
<div
className={`hidden md:flex md:items-center md:ml-8
${theme === "dark" ? "pt-1" : ""}
`}
css={
shouldShowDivider
? `
/*
here be dragons...
The next one is easier to read, read that first.
...welcome back. This one depends on the viewport width. 100vw - 64px is
now the total space reserved for the <main> area. Minus 280px for the sidebar,
and then the rest is the same. The only other difference is we use the max()
function because 2rem (the padding) will win when the content area starts
getting less than 720px.
*/
@media (min-width: 1024px) {
margin-left: max(
2rem,
2rem + ((100vw - 64px - 280px - 2rem - 720px) / 2)
);
}
/*
This is a magic number for screens 1220px and above. The sidebar is 280px,
leaving 1152px - 280px room for the main area. There's 2rem of padding, and
above @media(1220px) the main text area will be 720px. That leaves
(1152px - 280px - 2rem - 720px)
space left on either side of it for the dynamic margin value. Divid by 2
to get the dynamic margin-left value, then add back in the padding.
*/
@media (min-width: 1220px) {
margin-left: calc(
((1152px - 280px - 2rem - 720px) / 2) + 2rem
);
}
`
: `
@media (min-width: 1024px) {
margin-left: 4rem;
}
`
}
>
<div className={shouldShowDivider ? "-ml-1" : ""}>
<NavLink
to={router.routerFor("/docs").pages[0].url}
activeFor="/docs/*"
>
Guides
</NavLink>
<NavLink
to={router.routerFor("/tutorial").pages[0].url}
activeFor="/tutorial/*"
>
Tutorial
</NavLink>
<NavLink
to="/api/classes/association/"
activeFor="/api/*"
>
API
</NavLink>
<NavLink
to={router.routerFor("/quickstarts").pages[0].url}
activeFor="/quickstarts/*"
>
Quickstarts
</NavLink>
<NavLink to="/repl">REPL</NavLink>
</div>
</div>
</>
) : null}
<div className="hidden md:flex md:items-center md:ml-auto">
<button
onClick={() => setIsShowingSearch(!isShowingSearch)}
className={`focus:outline-none focus-visible:shadow-outline px-1 mr-5 ${themeClasses[theme]["inactive"]}`}
>
<svg viewBox="0 0 20 20" className="w-5 h-5 fill-current">
<title>Search</title>
<path
fillRule="evenodd"
d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z"
clipRule="evenodd"
></path>
</svg>
</button>
{/* <div
className={`w-px h-5 mr-8 border-l ${themeClasses[theme]["divider"]}`}
/> */}
<a
href="https://discord.gg/pPsdsrn"
className={`focus:outline-none focus-visible:shadow-outline px-1 mr-5 ${themeClasses[theme]["inactive"]}`}
>
<Discord className="h-5 fill-current" />
</a>
<a
href="https://twitter.com/miragejs"
className={`focus:outline-none focus-visible:shadow-outline px-1 mr-5 ${themeClasses[theme]["inactive"]}`}
>
<Twitter className="h-5 fill-current" />
</a>
<a
href="https://github.com/miragejs/miragejs"
className={`focus:outline-none focus-visible:shadow-outline px-1 ${themeClasses[theme]["inactive"]}`}
>
<Github className="h-5 fill-current" />
</a>
</div>
</div>
{/* Mobile nav */}
{isShowingMobileNav && (
<nav className="text-lg font-medium md:hidden">
<div
className={`border-t ${
theme === "dark" ? "border-gray-800" : "border-gray-200"
}`}
>
<MobileNavLink
to="/docs/getting-started/introduction/"
onClick={() => setIsShowingMobileNav(false)}
>
Guides
</MobileNavLink>
</div>
<div
className={`border-t ${
theme === "dark" ? "border-gray-800" : "border-gray-200"
}`}
>
<MobileNavLink
to={router.routerFor("/tutorial").pages[0].url}
onClick={() => setIsShowingMobileNav(false)}
>
Tutorial
</MobileNavLink>
</div>
<div
className={`border-t ${
theme === "dark" ? "border-gray-800" : "border-gray-200"
}`}
>
<MobileNavLink
to="/api/classes/association/"
onClick={() => setIsShowingMobileNav(false)}
>
API
</MobileNavLink>
</div>
<div
className={`border-t ${
theme === "dark" ? "border-gray-800" : "border-gray-200"
}`}
>
<MobileNavLink
to={router.routerFor("/quickstarts").pages[0].url}
onClick={() => setIsShowingMobileNav(false)}
>
Quickstarts
</MobileNavLink>
</div>
<div
className={`border-t ${
theme === "dark" ? "border-gray-800" : "border-gray-200"
}`}
>
<MobileNavLink
to="/repl"
onClick={() => setIsShowingMobileNav(false)}
>
REPL
</MobileNavLink>
</div>
<div
className={`border-t ${
theme === "dark" ? "border-gray-800" : "border-gray-200"
}`}
>
<MobileNavLink
to="https://github.com/miragejs/miragejs"
onClick={() => setIsShowingMobileNav(false)}
>
GitHub
</MobileNavLink>
</div>
</nav>
)}
</header>
</div>
</div>
{isShowingSearch && (
<DialogOverlay
className="bg-gray-900.50"
onDismiss={() => setIsShowingSearch(false)}
>
<DialogContent
aria-label="search"
style={{
marginTop: 0,
marginBottom: 0,
padding: 0,
width: "auto",
maxWidth: "36rem",
background: "transparent",
}}
>
<Search onSelect={handleSearchSelect} />
</DialogContent>
</DialogOverlay>
)}
</div>
)
}
function MobileNavLink(props) {
const { theme } = useTheme()
const baseClasses = `block px-5 py-4`
const isExternal = props.to.indexOf("http") === 0
const linkClasses = {
light: {
active: "text-gray-900",
inactive: "text-gray-600 hover:text-gray-900",
},
dark: {
active: "text-gray-100",
inactive: "text-gray-100 hover:text-gray-100",
},
}
let link
if (isExternal) {
link = (
<a
href={props.to}
{...props}
className={`${baseClasses} ${linkClasses[theme]["inactive"]}`}
>
{props.children}
</a>
)
} else {
const isPartiallyActive = ({ isPartiallyCurrent }) => {
let state = isPartiallyCurrent ? "active" : "inactive"
return {
className: `${baseClasses} ${linkClasses[theme][state]}`,
}
}
link = <Link {...props} getProps={isPartiallyActive} />
}
return link
}
function NavLink({ activeFor, ...props }) {
const { theme } = useTheme()
activeFor = activeFor || props.to
return (
<Match path={activeFor}>
{({ match }) => {
let state = match ? "active" : "inactive"
return (
<Link
{...props}
className={`focus:outline-none focus-visible:shadow-outline mr-5 lg:mr-7 px-1 font-medium ${themeClasses[theme][state]}`}
/>
)
}}
</Match>
)
}
let memoizedOutlet
function renderRoutes(routes) {
return (
routes.length > 0 &&
routes.map((route) => {
let explicitComponent =
routeComponentsMap[`./${route.fullName.replace(/\./g, "/")}`]
let EmptyComponent = (props) => <Fragment>{props.children}</Fragment>
let Component = explicitComponent
? explicitComponent.default
: EmptyComponent
return (
<Component path={route.path} key={route.fullName}>
{renderRoutes(route.routes)}
</Component>
)
})
)
}
function Outlet() {
let router = useRouter()
if (!memoizedOutlet) {
memoizedOutlet = renderRoutes(router.routes)
}
useEffect(() => {
if (!router.activePage && router.activeRoute) {
// we're not on a page, but we're somewhere in the router
// lets jump to the first rendering page
// tldr: /docs -> /docs/getting-started/introduction
let bestPage = router.activeRoute.pages[0]
if (!bestPage.isDynamic) {
navigate(bestPage.url, { replace: true })
}
}
}, [router.activePage, router.activeRoute])
return (
<Router primary={false} className="flex flex-col flex-1">
{memoizedOutlet}
<NotFound default />
</Router>
)
}
function Footer() {
let router = useRouter()
return (
<footer className="px-5 pt-16 pb-12 md:px-6 md:pb-20 bg-gray-1000 xl:px-16">
<div className="max-w-6xl mx-auto">
<div className="">
<div className="flex -mx-3 md:text-lg">
<div className="w-1/2 px-3 md:w-1/4">
<p className="py-1 text-sm tracking-wide text-gray-600 uppercase md:text-base">
Docs
</p>
<div className="mt-1">
<ul>
<li className="py-1 text-white">
<Link to={router.routerFor("/docs").pages[0].url}>
Guides
</Link>
</li>
<li className="py-1 text-white">
<Link to={router.routerFor("/tutorial").pages[0].url}>
Tutorial
</Link>
</li>
<li className="py-1 text-white">
<Link to="/api/classes/association/">API</Link>
</li>
<li className="py-1 text-white">
<Link to={router.routerFor("/quickstarts").pages[0].url}>
Quickstarts
</Link>
</li>
<li className="py-1 text-white">
<Link to="/repl">REPL</Link>
</li>
</ul>
</div>
</div>
<div className="w-1/2 px-3 md:w-1/4">
<p className="py-1 text-sm tracking-wide text-gray-600 uppercase md:text-base">
Community
</p>
<div className="mt-1">
<ul>
<li className="py-1 text-white">
<a href="https://github.com/miragejs/miragejs">GitHub</a>
</li>
<li className="py-1 text-white">
<a href="https://discord.gg/pPsdsrn">Discord</a>
</li>
<li className="py-1 text-white">
<a href="https://twitter.com/miragejs">Twitter</a>
</li>
</ul>
</div>
</div>
</div>
</div>
<div className="py-10 sm:py-12">
<div className="sm:border-t sm:border-gray-800" />
</div>
<div className="sm:flex">
<div className="w-full max-w-xl">
<SignupForm />
</div>
<div className="flex justify-center mt-16 sm:items-end sm:pl-32 sm:mt-0 sm:justify-end sm:ml-auto">
<Link to="/" className="block p-1">
<Logo className="w-8 sm:w-10" />
</Link>
</div>
</div>
</div>
</footer>
)
}
const AlgoliaStyles = createGlobalStyle`
.algolia-autocomplete {
display: block !important;
}
.algolia-autocomplete .ds-dropdown-menu {
width: 100%;
}
.algolia-autocomplete .suggestion-layout-simple .algolia-docsearch-suggestion--text .algolia-docsearch-suggestion--highlight{
color: red;
}
.algolia-autocomplete .ds-dropdown-menu .ds-suggestion.ds-cursor .algolia-docsearch-suggestion:not(.suggestion-layout-simple) .algolia-docsearch-suggestion--content {
background-color: rgba(5, 199, 126, .10)
}
.algolia-autocomplete .algolia-docsearch-suggestion--highlight {
color: rgba(3, 166, 103);
}
.algolia-autocomplete .algolia-docsearch-suggestion--category-header .algolia-docsearch-suggestion--category-header-lvl0 .algolia-docsearch-suggestion--highlight,.algolia-autocomplete .algolia-docsearch-suggestion--category-header .algolia-docsearch-suggestion--category-header-lvl1 .algolia-docsearch-suggestion--highlight,.algolia-autocomplete .algolia-docsearch-suggestion--text .algolia-docsearch-suggestion--highlight{
box-shadow: inset 0 -2px 0 0 rgba(3, 166, 103, .8);
}
`
function Search({ onSelect }) {
let inputRef = useRef()
useEffect(() => {
import("docsearch.js").then((module) => {
if (document.querySelector("#mirage-algolia-search-input")) {
module.default({
apiKey: "4df96bd592d6cdcc40aae9c4a76adc64",
indexName: "miragejs",
inputSelector: "#mirage-algolia-search-input",
debug: false, // Set debug to true to inspect the dropdown
handleSelected: function (
input,
event,
suggestion,
datasetNumber,
context
) {
onSelect(suggestion.url)
},
})
inputRef.current.focus()
}
})
})
// Seems like aloglia stops keys from propagating. Would like to make ctrl+n/p navigate list.
// useKeyboardShortcut("ctrl+n", () => {
// console.log("hi")
// })
return (
<>
<AlgoliaStyles />
<div className="flex items-center mt-24">
<div className="relative flex-1 rounded-md shadow-xl">
<input
id="mirage-algolia-search-input"
ref={inputRef}
className="block w-full px-5 py-4 text-lg rounded-lg focus:outline-none"
placeholder={`Search the docs (press "/" to focus)`}
/>
</div>
</div>
</>
)
}