Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(router): createPages #293

Merged
merged 22 commits into from
Dec 25, 2023
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Counter } from '../../components/Counter.js';
import { Counter } from './Counter.js';

const Bar = () => (
<div>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Counter } from '../../components/Counter.js';
import { Counter } from './Counter.js';

const Foo = () => (
<div>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const Baz = () => (
<div>
<h2>Nested</h2>
<h3>Baz</h3>
</div>
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
const Qux = () => (
<div>
<h2>Nested</h2>
<h3>Qux</h3>
</div>
);
Expand Down
89 changes: 59 additions & 30 deletions examples/07_router/src/entries.tsx
Original file line number Diff line number Diff line change
@@ -1,32 +1,61 @@
import { defineRouter } from 'waku/router/server';
import { lazy } from 'react';
import { createPages } from 'waku/router/server';

const STATIC_PATHS = ['/', '/foo', '/bar', '/nested/baz', '/nested/qux'];
const HomeLayout = lazy(() => import('./components/HomeLayout.js'));
const HomePage = lazy(() => import('./components/HomePage.js'));
const FooPage = lazy(() => import('./components/FooPage.js'));
const BarPage = lazy(() => import('./components/BarPage.js'));
const NestedBazPage = lazy(() => import('./components/NestedBazPage.js'));
const NestedQuxPage = lazy(() => import('./components/NestedQuxPage.js'));

export default defineRouter(
// existsPath
async (path: string) => (STATIC_PATHS.includes(path) ? 'static' : null),
// getComponent (id is "**/layout" or "**/page")
async (id, unstable_setShouldSkip) => {
unstable_setShouldSkip({}); // always skip if possible
switch (id) {
case 'layout':
return import('./routes/layout.js');
case 'page':
return import('./routes/page.js');
case 'foo/page':
return import('./routes/foo/page.js');
case 'bar/page':
return import('./routes/bar/page.js');
case 'nested/layout':
return import('./routes/nested/layout.js');
case 'nested/baz/page':
return import('./routes/nested/baz/page.js');
case 'nested/qux/page':
return import('./routes/nested/qux/page.js');
default:
return null;
}
},
// getPathsForBuild
async () => STATIC_PATHS.map((path) => ({ path })),
);
export default createPages(async ({ createPage }) => {
createPage({
render: 'static',
path: '/',
component: () => (
<HomeLayout>
<HomePage />
</HomeLayout>
),
});

createPage({
render: 'static',
path: '/foo',
component: () => (
<HomeLayout>
<FooPage />
</HomeLayout>
),
});

createPage({
render: 'static',
path: '/bar',
component: () => (
<HomeLayout>
<BarPage />
</HomeLayout>
),
});

createPage({
render: 'static',
path: '/nested/baz',
component: () => (
<HomeLayout>
<NestedBazPage />
</HomeLayout>
),
});

createPage({
render: 'static',
path: '/nested/qux',
component: () => (
<HomeLayout>
<NestedQuxPage />
</HomeLayout>
),
});
});
13 changes: 0 additions & 13 deletions examples/07_router/src/routes/nested/layout.tsx

This file was deleted.

122 changes: 121 additions & 1 deletion packages/waku/src/router/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ import {
SHOULD_SKIP_ID,
} from './common.js';
import type { RouteProps, ShouldSkip } from './common.js';
import { joinPath } from '../lib/utils/path.js';

const Default = ({ children }: { children: ReactNode }) => children;
const Default = ({ children }: RouteProps & { children: ReactNode }) =>
children;

const ShoudSkipComponent = ({ shouldSkip }: { shouldSkip: ShouldSkip }) =>
createElement('meta', {
Expand Down Expand Up @@ -146,3 +148,121 @@ globalThis.__WAKU_ROUTER_PREFETCH__ = (path, searchParams) => {

return { renderEntries, getBuildConfig, getSsrConfig };
}

// createPages API (a wrapper around defineRouter)

type NonEmpty<T> = T extends '' ? false : true;
type IsValidPath<T> = T extends `${infer L}/${infer R}`
? NonEmpty<L> extends true
? IsValidPath<R>
: false
: NonEmpty<T>;
type IsSlug<T> = T extends `[${infer U}]` ? NonEmpty<U> : false;
type IsNotSlug<T> = T extends `[${string}]` ? false : NonEmpty<T>;
type IsPathElementWithSlug<T> = T extends `${infer L}/${infer R}`
? IsSlug<L> extends true
? IsValidPath<R>
: IsPathElementWithSlug<R>
: IsSlug<T>;
type IsPathElementWithoutSlug<T> = T extends `${infer L}/${infer R}`
? IsNotSlug<L> extends true
? IsPathElementWithoutSlug<R>
: IsSlug<L> extends true
? false
: IsValidPath<R>
: IsNotSlug<T>;
type PathWithSlug<T> = T extends '/'
? T
: T extends `/${infer U}`
? IsPathElementWithSlug<U> extends true
? T
: never
: never;
type PathWithoutSlug<T> = T extends '/'
? T
: T extends `/${infer U}`
? IsPathElementWithoutSlug<U> extends true
? T
: never
: never;

type CreatePage = <T extends string>(
page:
| {
render: 'static';
path: PathWithoutSlug<T>;
component: FunctionComponent<RouteProps>;
}
| {
render: 'static';
path: PathWithSlug<T>;
staticPaths: string[] | string[][];
component: FunctionComponent<RouteProps>;
}
| {
render: 'dynamic';
path: PathWithoutSlug<T> | PathWithSlug<T>;
component: FunctionComponent<RouteProps>;
},
) => void;

type CreateLayout = <T extends string>(layout: {
render: 'static';
path: PathWithoutSlug<T>;
component: FunctionComponent<
Omit<RouteProps, 'searchParams'> & { children: ReactNode }
>;
}) => void;

export function createPages(
fn: (fns: {
createPage: CreatePage;
createLayout: CreateLayout;
}) => Promise<void>,
): ReturnType<typeof defineEntries> {
const staticPathSet = new Set<string>();
// TODO dynamic & wildcard
// const dynamicPaths: { item: string; isSlug: boolean }[] = [];
// const wildcardPaths: { item: string; isSlug: boolean }[] = [];
const componentMap = new Map<
string,
FunctionComponent<RouteProps & { children: ReactNode }>
>();
let finished = false;
const createPage: CreatePage = (page) => {
if (finished) {
throw new Error('no longer available');
}
staticPathSet.add(page.path);
const id = joinPath(page.path, 'page').replace(/^\//, '');
if (componentMap.has(id) && componentMap.get(id) !== page.component) {
throw new Error(`Duplicated component for: ${page.path}`);
}
componentMap.set(id, page.component);
};
const createLayout: CreateLayout = (layout) => {
if (finished) {
throw new Error('no longer available');
}
const id = joinPath(layout.path, 'layout').replace(/^\//, '');
if (componentMap.has(id) && componentMap.get(id) !== layout.component) {
throw new Error(`Duplicated component for: ${layout.component}`);
}
componentMap.set(id, layout.component);
};
const ready = fn({ createPage, createLayout }).then(() => {
finished = true;
});
return defineRouter(
async (path: string) => {
await ready;
return staticPathSet.has(path) ? 'static' : null;
},
async (id, unstable_setShouldSkip) => {
await ready;
unstable_setShouldSkip({}); // for static paths
return componentMap.get(id) || null;
},
async () => Array.from(staticPathSet).map((path) => ({ path })),
);
}
Loading