migrate docs back to remix oops

This commit is contained in:
MapleLeaf
2022-01-09 17:34:50 -06:00
parent c6ea101330
commit 7d8336c7a7
58 changed files with 2086 additions and 2531 deletions

View File

@@ -5,7 +5,8 @@
"**/.cache/**", "**/.cache/**",
"**/build/**", "**/build/**",
"**/dist/**", "**/dist/**",
"**/coverage/**" "**/coverage/**",
"**/public/**"
], ],
"parserOptions": { "parserOptions": {
"project": "./tsconfig.base.json" "project": "./tsconfig.base.json"

View File

@@ -8,8 +8,6 @@ RUN ls -R
RUN npm install -g pnpm RUN npm install -g pnpm
RUN pnpm install --unsafe-perm --frozen-lockfile RUN pnpm install --unsafe-perm --frozen-lockfile
RUN pnpm run build -C packages/docs RUN pnpm run build -C packages/docs
RUN pnpm install -C packages/docs --prod --unsafe-perm --frozen-lockfile
RUN pnpm store prune
ENV NODE_ENV=production ENV NODE_ENV=production
CMD [ "pnpm", "-C", "packages/docs", "serve" ] CMD [ "pnpm", "-C", "packages/docs", "start" ]

View File

@@ -1,3 +1,7 @@
.asset-cache
node_modules node_modules
/api
/.cache
/build
/public/build
.env
/public/api

53
packages/docs/README.md Normal file
View File

@@ -0,0 +1,53 @@
# Welcome to Remix!
- [Remix Docs](https://remix.run/docs)
## Development
From your terminal:
```sh
npm run dev
```
This starts your app in development mode, rebuilding assets on file changes.
## Deployment
First, build your app for production:
```sh
npm run build
```
Then run the app in production mode:
```sh
npm start
```
Now you'll need to pick a host to deploy it to.
### DIY
If you're familiar with deploying node applications, the built-in Remix app server is production-ready.
Make sure to deploy the output of `remix build`
- `build/`
- `public/build/`
### Using a Template
When you ran `npx create-remix@latest` there were a few choices for hosting. You can run that again to create a new project, then copy over your `app/` folder to the new project that's pre-configured for your target server.
```sh
cd ..
# create a new project, and pick a pre-configured host
npx create-remix@latest
cd my-new-remix-app
# remove the new project's app (not the old one!)
rm -rf app
# copy your app over
cp -R ../my-old-remix-app/app app
```

View File

@@ -0,0 +1,4 @@
import { hydrate } from "react-dom";
import { RemixBrowser } from "remix";
hydrate(<RemixBrowser />, document);

View File

@@ -0,0 +1,21 @@
import { renderToString } from "react-dom/server";
import { RemixServer } from "remix";
import type { EntryContext } from "remix";
export default function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext
) {
const markup = renderToString(
<RemixServer context={remixContext} url={request.url} />
);
responseHeaders.set("Content-Type", "text/html");
return new Response("<!DOCTYPE html>" + markup, {
status: responseStatusCode,
headers: responseHeaders
});
}

View File

@@ -1,4 +1,4 @@
<!-- prettier-ignore --> {/* prettier-ignore */}
```tsx ```tsx
import * as React from "react" import * as React from "react"
import { Embed, Button } from "reacord" import { Embed, Button } from "reacord"

View File

@@ -0,0 +1,31 @@
import type { ComponentPropsWithoutRef } from "react"
import { Link } from "remix"
export type AppLinkProps = ComponentPropsWithoutRef<"a"> & {
type: "internal" | "external" | "router"
to: string
}
export function AppLink({ type, to, children, ...props }: AppLinkProps) {
if (type === "internal") {
return (
<a href={to} {...props}>
{children}
</a>
)
}
if (type === "external") {
return (
<a href={to} target="_blank" rel="noopener noreferrer" {...props}>
{children}
</a>
)
}
return (
<Link to={to} {...props}>
{children}
</Link>
)
}

View File

@@ -0,0 +1,10 @@
import { createContext, useContext } from "react"
import type { GuideLink } from "~/modules/navigation/load-guide-links.server"
const Context = createContext<GuideLink[]>([])
export const GuideLinksProvider = Context.Provider
export function useGuideLinksContext() {
return useContext(Context)
}

View File

@@ -0,0 +1,40 @@
import glob from "fast-glob"
import grayMatter from "gray-matter"
import { readFile } from "node:fs/promises"
import { join, parse } from "node:path"
import type { AppLinkProps } from "~/modules/navigation/app-link"
const guidesFolder = "app/routes/guides"
export type GuideLink = {
title: string
order: number
link: AppLinkProps
}
export async function loadGuideLinks(): Promise<GuideLink[]> {
const guideFiles = await glob(`**/*.md`, { cwd: guidesFolder })
const links: GuideLink[] = await Promise.all(
guideFiles.map(async (file) => {
const { data } = grayMatter(await readFile(join(guidesFolder, file)))
let order = data.order
if (!Number.isFinite(order)) {
order = Number.POSITIVE_INFINITY
}
return {
title: data.meta?.title,
order,
link: {
type: "router",
to: `/guides/${parse(file).name}`,
children: data.meta?.title,
},
}
}),
)
return links.sort((a, b) => a.order - b.order)
}

View File

@@ -2,16 +2,15 @@ import {
CodeIcon, CodeIcon,
DocumentTextIcon, DocumentTextIcon,
ExternalLinkIcon, ExternalLinkIcon,
} from "@heroicons/react/solid/esm" } from "@heroicons/react/solid"
import React from "react" import type { AppLinkProps } from "~/modules/navigation/app-link"
import { inlineIconClass } from "../ui/components" import { inlineIconClass } from "../ui/components"
import type { AppLinkProps } from "./app-link"
export const mainLinks: AppLinkProps[] = [ export const mainLinks: AppLinkProps[] = [
{ {
type: "internal", type: "internal",
to: "/guides/getting-started", to: "/guides/getting-started",
label: ( children: (
<> <>
<DocumentTextIcon className={inlineIconClass} /> Guides <DocumentTextIcon className={inlineIconClass} /> Guides
</> </>
@@ -20,7 +19,7 @@ export const mainLinks: AppLinkProps[] = [
{ {
type: "internal", type: "internal",
to: "/api", to: "/api",
label: ( children: (
<> <>
<CodeIcon className={inlineIconClass} /> API Reference <CodeIcon className={inlineIconClass} /> API Reference
</> </>
@@ -29,7 +28,7 @@ export const mainLinks: AppLinkProps[] = [
{ {
type: "external", type: "external",
to: "https://github.com/itsMapleLeaf/reacord", to: "https://github.com/itsMapleLeaf/reacord",
label: ( children: (
<> <>
<ExternalLinkIcon className={inlineIconClass} /> GitHub <ExternalLinkIcon className={inlineIconClass} /> GitHub
</> </>

View File

@@ -1,11 +1,11 @@
import React from "react" import { useGuideLinksContext } from "~/modules/navigation/guide-links-context"
import { linkClass } from "../ui/components" import { linkClass } from "../ui/components"
import { PopoverMenu } from "../ui/popover-menu" import { PopoverMenu } from "../ui/popover-menu"
import { AppLink } from "./app-link" import { AppLink } from "./app-link"
import { guideLinks } from "./guide-links"
import { mainLinks } from "./main-links" import { mainLinks } from "./main-links"
export function MainNavigation() { export function MainNavigation() {
const guideLinks = useGuideLinksContext()
return ( return (
<nav className="flex justify-between items-center h-16"> <nav className="flex justify-between items-center h-16">
<a href="/"> <a href="/">
@@ -26,7 +26,7 @@ export function MainNavigation() {
/> />
))} ))}
<hr className="border-0 h-[2px] bg-black/50" /> <hr className="border-0 h-[2px] bg-black/50" />
{guideLinks.map((link) => ( {guideLinks.map(({ link }) => (
<AppLink <AppLink
{...link} {...link}
key={link.to} key={link.to}

View File

@@ -1,4 +1,4 @@
import { MenuAlt4Icon } from "@heroicons/react/outline/esm" import { MenuAlt4Icon } from "@heroicons/react/outline"
import clsx from "clsx" import clsx from "clsx"
import React from "react" import React from "react"
import { linkClass } from "./components" import { linkClass } from "./components"

View File

@@ -0,0 +1,9 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer utilities {
.prose aside {
@apply opacity-75 italic border-l-4 pl-3 border-white/50;
}
}

4
packages/docs/app/react.d.ts vendored Normal file
View File

@@ -0,0 +1,4 @@
import "react"
declare module "react" {
export function createContext<Value>(): Context<Value | undefined>
}

2
packages/docs/app/remix.env.d.ts vendored Normal file
View File

@@ -0,0 +1,2 @@
/// <reference types="@remix-run/dev" />
/// <reference types="@remix-run/node/globals" />

View File

@@ -0,0 +1,68 @@
import packageJson from "reacord/package.json"
import type { LinksFunction, LoaderFunction, MetaFunction } from "remix"
import {
Links,
LiveReload,
Meta,
Outlet,
ScrollRestoration,
useLoaderData,
} from "remix"
import { GuideLinksProvider } from "~/modules/navigation/guide-links-context"
import type { GuideLink } from "~/modules/navigation/load-guide-links.server"
import { loadGuideLinks } from "~/modules/navigation/load-guide-links.server"
import prismThemeCss from "~/modules/ui/prism-theme.css"
export const meta: MetaFunction = () => ({
title: "Reacord",
description: packageJson.description,
})
export const links: LinksFunction = () => [
{ rel: "preconnect", href: "https://fonts.googleapis.com" },
{
rel: "preconnect",
href: "https://fonts.gstatic.com",
crossOrigin: "anonymous",
},
{
rel: "preload",
as: "style",
href: "https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@500&family=Rubik:ital,wght@0,300;0,400;0,500;1,300;1,400;1,500&display=swap",
},
{ rel: "stylesheet", href: "/tailwind.css" },
{ rel: "stylesheet", href: prismThemeCss },
]
type LoaderData = {
guideLinks: GuideLink[]
}
export const loader: LoaderFunction = async () => {
const data: LoaderData = {
guideLinks: await loadGuideLinks(),
}
return data
}
export default function App() {
const data: LoaderData = useLoaderData()
return (
<html lang="en" className="bg-slate-900 text-slate-100">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<Meta />
<Links />
<script defer src="//unpkg.com/alpinejs@3.7.1" />
</head>
<body>
<GuideLinksProvider value={data.guideLinks}>
<Outlet />
</GuideLinksProvider>
<ScrollRestoration />
{process.env.NODE_ENV === "development" && <LiveReload />}
</body>
</html>
)
}

View File

@@ -0,0 +1,38 @@
import clsx from "clsx"
import { Outlet } from "remix"
import { AppLink } from "~/modules/navigation/app-link"
import { useGuideLinksContext } from "~/modules/navigation/guide-links-context"
import { MainNavigation } from "~/modules/navigation/main-navigation"
import {
docsProseClass,
linkClass,
maxWidthContainer,
} from "~/modules/ui/components"
export default function GuidePage() {
const guideLinks = useGuideLinksContext()
return (
<>
<header className="bg-slate-700/30 shadow sticky top-0 backdrop-blur-sm transition z-10 flex">
<div className={maxWidthContainer}>
<MainNavigation />
</div>
</header>
<main className={clsx(maxWidthContainer, "mt-8 flex items-start gap-4")}>
<nav className="w-48 sticky top-24 hidden md:block">
<h2 className="text-2xl">Guides</h2>
<ul className="mt-3 flex flex-col gap-2 items-start">
{guideLinks.map(({ link }) => (
<li key={link.to}>
<AppLink {...link} className={linkClass} />
</li>
))}
</ul>
</nav>
<section className={clsx(docsProseClass, "pb-8 flex-1 min-w-0")}>
<Outlet />
</section>
</main>
</>
)
}

View File

@@ -1,5 +1,6 @@
--- ---
order: 3 order: 3
meta:
title: Buttons title: Buttons
description: Using button components description: Using button components
--- ---

View File

@@ -1,4 +1,5 @@
--- ---
meta:
title: Using Reacord with other libraries title: Using Reacord with other libraries
description: Adapting Reacord to another Discord library description: Adapting Reacord to another Discord library
--- ---

View File

@@ -1,5 +1,6 @@
--- ---
order: 2 order: 2
meta:
title: Embeds title: Embeds
description: Using embed components description: Using embed components
--- ---

View File

@@ -1,5 +1,6 @@
--- ---
order: 0 order: 0
meta:
title: Getting Started title: Getting Started
description: Learn how to get started with Reacord. description: Learn how to get started with Reacord.
--- ---

View File

@@ -1,5 +1,6 @@
--- ---
order: 4 order: 4
meta:
title: Select Menus title: Select Menus
description: Using select menu components description: Using select menu components
--- ---

View File

@@ -1,5 +1,6 @@
--- ---
order: 1 order: 1
meta:
title: Sending Messages title: Sending Messages
description: Sending messages by creating Reacord instances description: Sending messages by creating Reacord instances
--- ---

View File

@@ -0,0 +1,29 @@
import packageJson from "reacord/package.json"
import LandingExample from "~/modules/landing/landing-example.mdx"
import { MainNavigation } from "~/modules/navigation/main-navigation"
import { maxWidthContainer } from "~/modules/ui/components"
export default function Landing() {
return (
<div className="flex flex-col min-w-0 min-h-screen text-center">
<header className={maxWidthContainer}>
<MainNavigation />
</header>
<div className="px-4 pb-8 flex flex-1">
<main className="px-4 py-6 rounded-lg shadow bg-slate-800 space-y-5 m-auto w-full max-w-xl">
<h1 className="text-6xl font-light">reacord</h1>
<section className="mx-auto text-sm sm:text-base">
<LandingExample />
</section>
<p className="text-2xl font-light">{packageJson.description}</p>
<a
href="/guides/getting-started"
className="inline-block px-4 py-3 text-xl transition rounded-lg bg-emerald-700 hover:translate-y-[-2px] hover:bg-emerald-800 hover:shadow"
>
Get Started
</a>
</main>
</div>
</div>
)
}

View File

@@ -0,0 +1,5 @@
import type { LoaderFunction } from "remix"
import { serveTailwindCss } from "remix-tailwind"
export const loader: LoaderFunction = () =>
serveTailwindCss("app/modules/ui/tailwind.css")

View File

@@ -1,60 +1,44 @@
{ {
"name": "reacord-docs",
"type": "module",
"private": true, "private": true,
"name": "reacord-docs-new",
"scripts": { "scripts": {
"prepare": "node ./scripts/fix-heroicons.js", "prepare": "remix setup node",
"serve": "esmo --experimental-import-meta-resolve --experimental-json-modules --no-warnings src/main.tsx | pino-colada", "dev": "concurrently 'typedoc --watch' 'remix dev'",
"dev": "npm-run-all --parallel --print-label --race dev-*", "build": "typedoc && remix build",
"dev-server": "nodemon --inspect --enable-source-maps --exec \"pnpm serve\" --watch src --ext ts,tsx,md,css", "start": "remix-serve build",
"dev-docs": "typedoc --watch",
"build": "typedoc",
"typecheck": "tsc --noEmit" "typecheck": "tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@heroicons/react": "^1.0.5", "@heroicons/react": "^1.0.5",
"@remix-run/react": "^1.1.1",
"@remix-run/serve": "^1.1.1",
"@tailwindcss/typography": "^0.5.0", "@tailwindcss/typography": "^0.5.0",
"alpinejs": "^3.7.1",
"autoprefixer": "^10.4.2", "autoprefixer": "^10.4.2",
"clsx": "^1.1.1", "clsx": "^1.1.1",
"compression": "^1.7.4",
"cross-env": "^7.0.3",
"cssnano": "^5.0.15",
"esbuild": "^0.14.10",
"esno": "^0.13.0",
"express": "^4.17.2",
"express-promise-router": "^4.1.1",
"fast-glob": "^3.2.10", "fast-glob": "^3.2.10",
"gray-matter": "^4.0.3", "gray-matter": "^4.0.3",
"http-terminator": "^3.0.4",
"markdown-it": "^12.3.2",
"markdown-it-prism": "^2.2.2",
"pino": "^7.6.2",
"pino-colada": "^2.2.2",
"pino-http": "^6.5.0",
"postcss": "^8.4.5", "postcss": "^8.4.5",
"reacord": "workspace:*", "reacord": "workspace:*",
"react": "^18.0.0-rc.0", "react": "^17.0.2",
"react-dom": "^18.0.0-rc.0", "react-dom": "^17.0.2",
"react-ssr-prepass": "^1.5.0", "remix": "^1.1.1",
"remix-tailwind": "^0.2.1",
"tailwindcss": "^3.0.12" "tailwindcss": "^3.0.12"
}, },
"devDependencies": { "devDependencies": {
"@types/browser-sync": "^2.26.3", "@remix-run/dev": "^1.1.1",
"@types/compression": "^1.7.2", "@remix-run/node": "^1.1.1",
"@types/cssnano": "^5.0.0",
"@types/express": "^4.17.13",
"@types/markdown-it": "^12.2.3",
"@types/node": "*", "@types/node": "*",
"@types/react": "^17.0.38", "@types/react": "^17.0.38",
"@types/react-dom": "^17.0.9", "@types/react-dom": "^17.0.11",
"@types/tailwindcss": "^3.0.2", "@types/tailwindcss": "^3.0.2",
"@types/wait-on": "^5.3.1", "concurrently": "^7.0.0",
"browser-sync": "^2.27.7", "rehype-prism-plus": "^1.2.2",
"nodemon": "^2.0.15",
"npm-run-all": "^4.1.5",
"type-fest": "^2.9.0",
"typedoc": "^0.22.10", "typedoc": "^0.22.10",
"typescript": "^4.5.4" "typescript": "^4.5.4"
} },
"engines": {
"node": ">=14"
},
"sideEffects": false
} }

View File

@@ -1,6 +0,0 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

@@ -0,0 +1,18 @@
/* eslint-disable unicorn/prefer-module */
/**
* @type {import('@remix-run/dev/config').AppConfig}
*/
module.exports = {
appDirectory: "app",
assetsBuildDirectory: "public/build",
publicPath: "/build/",
serverBuildDirectory: "build",
devServerPort: 8002,
ignoredRouteFiles: [".*"],
mdx: async () => {
const rehypePrism = await import("rehype-prism-plus")
return {
rehypePlugins: [rehypePrism.default],
}
},
}

View File

@@ -1,15 +0,0 @@
// heroicons doesn't have "sideEffects": false in it's package json,
// which causes esbuild to bundle in 460+ imports of react for some reason,
// which causes memory issues
import glob from "fast-glob"
import { readFile, writeFile } from "node:fs/promises"
const files = await glob("node_modules/@heroicons/react/**/*.json", {
absolute: true,
})
for (const file of files) {
const data = JSON.parse(await readFile(file, "utf8"))
data.sideEffects = false
await writeFile(file, JSON.stringify(data, undefined, 2))
}

View File

@@ -1,10 +0,0 @@
import { createContext, useContext } from "react"
import type { AssetBuilder } from "../asset-builder/asset-builder.js"
import { raise } from "../helpers/raise.js"
const Context = createContext<AssetBuilder>()
export const AssetBuilderProvider = Context.Provider
export const useAssetBuilder = () =>
useContext(Context) ?? raise("AssetBuilderProvider not found")

View File

@@ -1,96 +0,0 @@
import type { RequestHandler } from "express"
import express from "express"
import { createHash } from "node:crypto"
import { mkdir, rm } from "node:fs/promises"
import { join, parse } from "node:path"
import React from "react"
import { renderToStaticMarkup } from "react-dom/server"
import ssrPrepass from "react-ssr-prepass"
import type { Promisable } from "type-fest"
import { ensureWrite, normalizeAsFilePath } from "../helpers/filesystem.js"
import { AssetBuilderProvider } from "./asset-builder-context.js"
export type AssetTransformer<Asset> = {
transform: (context: AssetTransformContext) => Promise<Asset>
}
export class AssetBuilder {
private constructor(private cacheFolder: string) {}
static async create(cacheFolder: string) {
if (process.env.NODE_ENV !== "production") {
await rm(cacheFolder, { recursive: true }).catch(() => {})
}
await mkdir(cacheFolder, { recursive: true })
return new AssetBuilder(cacheFolder)
}
async build<Asset>(
input: Promisable<string | URL>,
transformer: AssetTransformer<Asset>,
alias?: string,
): Promise<Asset> {
const inputFile = normalizeAsFilePath(await input)
// TODO: cache assets by inputFile in production
return transformer.transform(
new AssetTransformContext({
inputFile,
cacheFolder: this.cacheFolder,
alias: alias || parse(inputFile).name,
}),
)
}
async render(element: React.ReactElement) {
element = (
<AssetBuilderProvider value={this}>
<React.Suspense fallback={<></>}>{element}</React.Suspense>
</AssetBuilderProvider>
)
await ssrPrepass(element)
return `<!DOCTYPE html>\n${renderToStaticMarkup(element)}`
}
middleware(): RequestHandler {
return express.static(this.cacheFolder, {
immutable: true,
maxAge: "1y",
})
}
}
export type AssetTransformOptions = {
inputFile: string
cacheFolder: string
alias: string
}
export class AssetTransformContext {
constructor(private options: AssetTransformOptions) {}
get inputFile() {
return this.options.inputFile
}
get cacheFolder() {
return this.options.cacheFolder
}
get alias() {
return this.options.alias
}
getOutputFileName(content: string) {
const { ext } = parse(this.inputFile)
const hash = createHash("sha256").update(content).digest("hex").slice(0, 8)
return `${this.alias}.${hash}${ext}`
}
async writeOutputFile(content: string) {
const outputFileName = this.getOutputFileName(content)
const outputFile = join(this.cacheFolder, outputFileName)
await ensureWrite(outputFile, content)
return { outputFileName, outputFile }
}
}

View File

@@ -1,75 +0,0 @@
import type { ReactNode } from "react";
import React from "react"
import { normalizeAsFilePath } from "../helpers/filesystem.js"
import { useAssetBuilder } from "./asset-builder-context.js"
import type { AssetBuilder, AssetTransformer } from "./asset-builder.js"
type AssetState =
| { status: "building"; promise: Promise<unknown> }
| { status: "built"; asset: unknown }
const cache = new Map<string, AssetState>()
function useAssetBuild<Asset>(
cacheKey: string,
build: (builder: AssetBuilder) => Promise<Asset>,
) {
const builder = useAssetBuilder()
const state = cache.get(cacheKey)
if (!state) {
const promise = build(builder).then((asset) => {
cache.set(cacheKey, { status: "built", asset })
})
cache.set(cacheKey, { status: "building", promise })
throw promise
}
if (state.status === "building") {
throw state.promise
}
return state.asset as Asset
}
export function LocalFileAsset<Asset>({
from,
using: transformer,
as: alias,
children,
}: {
from: string | URL
using: AssetTransformer<Asset>
as?: string
children: (url: Asset) => ReactNode
}) {
const inputFile = normalizeAsFilePath(from)
const asset = useAssetBuild(inputFile, (builder) => {
return builder.build(inputFile, transformer, alias)
})
return <>{children(asset)}</>
}
export function ModuleAsset<Asset>({
from,
using: transformer,
as: name,
children,
}: {
from: string
using: AssetTransformer<Asset>
as?: string
children: (url: Asset) => ReactNode
}) {
const cacheKey = `node:${from}`
const asset = useAssetBuild(cacheKey, async (builder) => {
const inputFile = await import.meta.resolve!(from)
return await builder.build(inputFile, transformer, name)
})
return <>{children(asset)}</>
}

View File

@@ -1,29 +0,0 @@
import grayMatter from "gray-matter"
import MarkdownIt from "markdown-it"
import prism from "markdown-it-prism"
import { readFile } from "node:fs/promises"
import type { AssetTransformer } from "./asset-builder.jsx"
const renderer = new MarkdownIt({
html: true,
linkify: true,
}).use(prism)
export type MarkdownAsset = {
content: { __html: string }
data: Record<string, any>
}
export const markdownTransformer: AssetTransformer<MarkdownAsset> = {
async transform(context) {
const { data, content } = grayMatter(
await readFile(context.inputFile, "utf8"),
)
const html = renderer.render(content)
return {
content: { __html: html },
data,
}
},
}

View File

@@ -1,26 +0,0 @@
import { build } from "esbuild"
import type { AssetTransformer } from "./asset-builder.jsx"
type ScriptAsset = {
url: string
}
export const scriptTransformer: AssetTransformer<ScriptAsset> = {
async transform(context) {
const scriptBuild = await build({
entryPoints: [context.inputFile],
bundle: true,
target: ["chrome89", "firefox89"],
format: "esm",
write: false,
minify: process.env.NODE_ENV === "production",
})
const content = scriptBuild.outputFiles[0]!.text
const { outputFileName } = await context.writeOutputFile(content)
return {
url: "/" + outputFileName,
}
},
}

View File

@@ -1,26 +0,0 @@
import autoprefixer from "autoprefixer"
import cssnano from "cssnano"
import { readFile } from "node:fs/promises"
import type { AcceptedPlugin } from "postcss"
import postcss from "postcss"
import tailwindcss from "tailwindcss"
import type { AssetTransformer } from "./asset-builder.jsx"
export type StylesheetAsset = { url: string }
export const stylesheetTransformer: AssetTransformer<StylesheetAsset> = {
async transform(context) {
const plugins: AcceptedPlugin[] = [tailwindcss, autoprefixer]
if (process.env.NODE_ENV === "production") {
plugins.push(cssnano)
}
const result = await postcss(plugins).process(
await readFile(context.inputFile),
{ from: context.inputFile },
)
const { outputFileName } = await context.writeOutputFile(result.css)
return { url: "/" + outputFileName }
},
}

View File

@@ -1,7 +0,0 @@
import { join } from "node:path"
const projectRoot = new URL("../", import.meta.url).pathname
export function fromProjectRoot(...subPaths: string[]) {
return join(projectRoot, ...subPaths)
}

View File

@@ -1,10 +0,0 @@
import type { ComponentPropsWithoutRef } from "react"
import React from "react"
export function ExternalLink(props: ComponentPropsWithoutRef<"a">) {
return (
<a target="_blank" rel="noopener noreferrer" {...props}>
{props.children}
</a>
)
}

View File

@@ -1,56 +0,0 @@
import clsx from "clsx"
import React from "react"
import { LocalFileAsset } from "../asset-builder/asset.js"
import { markdownTransformer } from "../asset-builder/markdown-transformer.js"
import { Html } from "../html.js"
import { AppLink } from "../navigation/app-link"
import { guideLinks } from "../navigation/guide-links"
import { MainNavigation } from "../navigation/main-navigation"
import { docsProseClass, linkClass, maxWidthContainer } from "../ui/components"
export function GuidePage({ url }: { url: string }) {
return (
<LocalFileAsset
from={new URL(`${url}.md`, import.meta.url)}
using={markdownTransformer}
>
{(asset) => (
<Html title={asset.data.title} description={asset.data.description}>
<Header />
<Body content={asset.content} />
</Html>
)}
</LocalFileAsset>
)
}
function Header() {
return (
<header className="bg-slate-700/30 shadow sticky top-0 backdrop-blur-sm transition z-10 flex">
<div className={maxWidthContainer}>
<MainNavigation />
</div>
</header>
)
}
function Body({ content }: { content: { __html: string } }) {
return (
<main className={clsx(maxWidthContainer, "mt-8 flex items-start gap-4")}>
<nav className="w-48 sticky top-24 hidden md:block">
<h2 className="text-2xl">Guides</h2>
<ul className="mt-3 flex flex-col gap-2 items-start">
{guideLinks.map((link) => (
<li key={link.to}>
<AppLink {...link} className={linkClass} />
</li>
))}
</ul>
</nav>
<section
className={clsx(docsProseClass, "pb-8 flex-1 min-w-0")}
dangerouslySetInnerHTML={content}
/>
</main>
)
}

View File

@@ -1,11 +0,0 @@
import { mkdir, writeFile } from "node:fs/promises"
import { dirname } from "node:path"
export async function ensureWrite(file: string, content: string) {
await mkdir(dirname(file), { recursive: true })
await writeFile(file, content)
}
export function normalizeAsFilePath(file: string | URL) {
return new URL(file, "file:").pathname
}

View File

@@ -1,15 +0,0 @@
import grayMatter from "gray-matter"
import MarkdownIt from "markdown-it"
import prism from "markdown-it-prism"
import { readFile } from "node:fs/promises"
const renderer = new MarkdownIt({
html: true,
linkify: true,
}).use(prism)
export async function renderMarkdownFile(filePath: string) {
const { data, content } = grayMatter(await readFile(filePath, "utf8"))
const html = renderer.render(content)
return { html, data }
}

View File

@@ -1,70 +0,0 @@
import packageJson from "reacord/package.json"
import type { ReactNode } from "react"
import React from "react"
import { LocalFileAsset, ModuleAsset } from "./asset-builder/asset.js"
import { scriptTransformer } from "./asset-builder/script-transformer.js"
import { stylesheetTransformer } from "./asset-builder/stylesheet-transformer.js"
export function Html({
title: titleProp,
description = packageJson.description,
children,
}: {
title?: string
description?: string
children: ReactNode
}) {
const title = [titleProp, "Reacord"].filter(Boolean).join(" | ")
return (
<html lang="en" className="bg-slate-900 text-slate-100">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<meta name="description" content={description} />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link
rel="preconnect"
href="https://fonts.gstatic.com"
crossOrigin=""
/>
<link
rel="preload"
as="style"
href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@500&family=Rubik:ital,wght@0,300;0,400;0,500;1,300;1,400;1,500&display=swap"
/>
<ModuleAsset
from="tailwindcss/tailwind.css"
using={stylesheetTransformer}
>
{(asset) => <link rel="stylesheet" href={asset.url} />}
</ModuleAsset>
<LocalFileAsset
from={new URL("ui/prism-theme.css", import.meta.url)}
using={stylesheetTransformer}
>
{(asset) => <link rel="stylesheet" href={asset.url} />}
</LocalFileAsset>
<LocalFileAsset
from={new URL("ui/markdown.css", import.meta.url)}
using={stylesheetTransformer}
>
{(asset) => <link rel="stylesheet" href={asset.url} />}
</LocalFileAsset>
<title>{title}</title>
<ModuleAsset
from="alpinejs/dist/cdn.js"
as="alpine"
using={scriptTransformer}
>
{(asset) => <script defer src={asset.url} />}
</ModuleAsset>
</head>
<body>{children}</body>
</html>
)
}

View File

@@ -1,42 +0,0 @@
import packageJson from "reacord/package.json"
import React from "react"
import { LocalFileAsset } from "../asset-builder/asset.js"
import { markdownTransformer } from "../asset-builder/markdown-transformer.js"
import { Html } from "../html.js"
import { MainNavigation } from "../navigation/main-navigation"
import { maxWidthContainer } from "../ui/components"
export function Landing() {
return (
<Html>
<div className="flex flex-col min-w-0 min-h-screen text-center">
<header className={maxWidthContainer}>
<MainNavigation />
</header>
<div className="px-4 pb-8 flex flex-1">
<main className="px-4 py-6 rounded-lg shadow bg-slate-800 space-y-5 m-auto w-full max-w-xl">
<h1 className="text-6xl font-light">reacord</h1>
<LocalFileAsset
from={new URL("landing-example.md", import.meta.url)}
using={markdownTransformer}
>
{(asset) => (
<section
className="mx-auto text-sm sm:text-base"
dangerouslySetInnerHTML={asset.content}
/>
)}
</LocalFileAsset>
<p className="text-2xl font-light">{packageJson.description}</p>
<a
href="/guides/getting-started"
className="inline-block px-4 py-3 text-xl transition rounded-lg bg-emerald-700 hover:translate-y-[-2px] hover:bg-emerald-800 hover:shadow"
>
Get Started
</a>
</main>
</div>
</div>
</Html>
)
}

View File

@@ -1,61 +0,0 @@
import compression from "compression"
import type { ErrorRequestHandler, Request } from "express"
import express from "express"
import PromiseRouter from "express-promise-router"
import httpTerminator from "http-terminator"
import pino from "pino"
import pinoHttp from "pino-http"
import * as React from "react"
import { AssetBuilder } from "./asset-builder/asset-builder.js"
import { fromProjectRoot } from "./constants"
import { GuidePage } from "./guides/guide-page"
import { Landing } from "./landing/landing"
const port = process.env.PORT || 3000
const builder = await AssetBuilder.create(fromProjectRoot(".asset-cache"))
const logger = pino()
const errorHandler: ErrorRequestHandler = (error, request, response, next) => {
response.status(500).send(error.message)
logger.error(error)
}
const router = PromiseRouter()
.use(pinoHttp({ logger }))
.use(compression())
.use(builder.middleware())
.use("/api", express.static("dist/api"))
.get("/guides/*", async (req: Request<{ 0: string }>, res) => {
res
.type("html")
.send(await builder.render(<GuidePage url={req.params[0]} />))
})
.get("/", async (req, res) => {
res.type("html").send(await builder.render(<Landing />))
})
.use(errorHandler)
const server = express()
.use(router)
.listen(port, () => {
logger.info(`Server is running on http://localhost:${port}`)
})
const terminator = httpTerminator.createHttpTerminator({ server })
process.on("SIGINT", () => {
terminator
.terminate()
.then(() => {
logger.info("Server terminated")
})
.catch((error) => {
logger.error(error)
})
.finally(() => {
process.exit()
})
})

View File

@@ -1,27 +0,0 @@
import React from "react"
import { ExternalLink } from "../dom/external-link"
export type AppLinkProps = {
type: "internal" | "external"
label: React.ReactNode
to: string
className?: string
}
export function AppLink(props: AppLinkProps) {
switch (props.type) {
case "internal":
return (
<a className={props.className} href={props.to}>
{props.label}
</a>
)
case "external":
return (
<ExternalLink className={props.className} href={props.to}>
{props.label}
</ExternalLink>
)
}
}

View File

@@ -1,34 +0,0 @@
import glob from "fast-glob"
import grayMatter from "gray-matter"
import { readFile } from "node:fs/promises"
import { join } from "node:path"
import type { AppLinkProps } from "./app-link"
const docsFolder = new URL("../guides", import.meta.url).pathname
const guideFiles = await glob("**/*.md", { cwd: docsFolder })
const entries = await Promise.all(
guideFiles.map(async (file) => {
const content = await readFile(join(docsFolder, file), "utf-8")
const { data } = grayMatter(content)
let order = Number(data.order)
if (!Number.isFinite(order)) {
order = Number.POSITIVE_INFINITY
}
return {
route: `/guides/${file.replace(/\.mdx?$/, "")}`,
title: String(data.title || ""),
order,
}
}),
)
export const guideLinks: AppLinkProps[] = entries
.sort((a, b) => a.order - b.order)
.map((item) => ({
type: "internal",
label: item.title,
to: item.route,
}))

View File

@@ -1,10 +0,0 @@
import "react"
declare module "react" {
export function createContext<Value>(): Context<Value | undefined>
}
declare module "react-dom" {
export function createRoot(element: Element): {
render(element: React.ReactNode): void
}
}

View File

@@ -1,3 +0,0 @@
.prose aside {
@apply opacity-75 italic border-l-4 pl-3 border-white/50;
}

View File

@@ -1,38 +0,0 @@
import clsx from "clsx"
const menus = document.querySelectorAll("[data-popover]")
for (const menu of menus) {
const button = menu.querySelector<HTMLButtonElement>("[data-popover-button]")!
const panel = menu.querySelector<HTMLDivElement>("[data-popover-panel]")!
const panelClasses = clsx`${panel.className} transition-all`
const visibleClass = clsx`${panelClasses} visible opacity-100 translate-y-0`
const hiddenClass = clsx`${panelClasses} invisible opacity-0 translate-y-2`
let visible = false
const setVisible = (newVisible: boolean) => {
visible = newVisible
panel.className = visible ? visibleClass : hiddenClass
if (!visible) return
requestAnimationFrame(() => {
const handleClose = (event: MouseEvent) => {
if (panel.contains(event.target as Node)) return
setVisible(false)
window.removeEventListener("click", handleClose)
}
window.addEventListener("click", handleClose)
})
}
const toggleVisible = () => setVisible(!visible)
button.addEventListener("click", toggleVisible)
setVisible(false)
panel.hidden = false
}

View File

@@ -1,6 +1,6 @@
// @ts-nocheck // @ts-nocheck
module.exports = { module.exports = {
content: ["./src/**/*.{ts,tsx,md}"], content: ["./app/**/*.{ts,tsx,md}"],
theme: { theme: {
fontFamily: { fontFamily: {
sans: ["Rubik", "sans-serif"], sans: ["Rubik", "sans-serif"],

View File

@@ -1,3 +1,9 @@
{ {
"extends": "../../tsconfig.base.json" "extends": "../../tsconfig.base.json",
"compilerOptions": {
"jsx": "react-jsx",
"paths": {
"~/*": ["./app/*"]
}
}
} }

View File

@@ -1,6 +1,6 @@
{ {
"entryPoints": ["../reacord/library/main.ts"], "entryPoints": ["../reacord/library/main.ts"],
"out": ["dist/api"], "out": ["public/api"],
"tsconfig": "../reacord/tsconfig.json", "tsconfig": "../reacord/tsconfig.json",
"excludeInternal": true, "excludeInternal": true,
"excludePrivate": true, "excludePrivate": true,

3480
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,2 +1,2 @@
docker build -t reacord . docker build -t reacord . &&
docker run -t -p 3000:3000 reacord docker run -t -p 3000:3000 reacord