Skip to content

Commit

Permalink
Release 1.5.0
Browse files Browse the repository at this point in the history
Release 1.5.0
  • Loading branch information
tj-kev committed Feb 24, 2022
2 parents 09807a3 + 9fb43e3 commit 6416b67
Show file tree
Hide file tree
Showing 12 changed files with 147 additions and 25 deletions.
9 changes: 8 additions & 1 deletion configs/webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,19 @@ module.exports = function ({ dev, isServer }) {
loader: MiniCssExtractPlugin.loader,
};

let sassOptionFiber = false;

// Check if we can enable fibers or not. Its not supported in node versions 16 and up.
if (parseInt(process.versions.node.split('.')[0]) < 16) {
sassOptionFiber = require("fibers");
}

const sassLoader = {
loader: "sass-loader",
options: {
implementation: require("sass"),
sassOptions: {
fiber: require("fibers"),
fiber: sassOptionFiber
},
},
};
Expand Down
36 changes: 35 additions & 1 deletion docs/custom-404-error-page.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ Accessing a path that has no corresponding [page](/docs/pages) will give the fol
could not find some-path/index.html in your content namespace
```

## Static html page

If you want to customize the 404 Not Found page for your application, you can add a static `404.html` HTML document in `/public`:

```html
Expand All @@ -24,4 +26,36 @@ If you want to customize the 404 Not Found page for your application, you can ad

You can reference other assets, such as stylesheets and images, stored as [static files](/docs/static-file-serving) from within the HTML document.

Note that it is currently **not possible to use a React page component** from `/pages` to generate the 404 Not Found page.
## React powered 404 page

To create a custom React powered 404 page you can create a `pages/404.js` file.

```
// pages/404.js
export async function getEdgeProps() {
const data = await someFallbackDataRequest();
return {
props: {
data,
},
notFound: true, // send 404 header
revalidate: 60, // Revalidate your data once every 60 seconds
}
}
export default function Index({ data }) {
return (
<div>
<h1>404 Not Found </h1>
<ul>
{data.map((item) => {
return <li key={item.id}>...</li>;
})}
</ul>
</div>
)
}
```

Note: `404.js` will take precedence over `404.html`. A 404 response will be returned on hard page loads only.
18 changes: 18 additions & 0 deletions docs/custom-headers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Custom Headers

Often times, you want to set custom response headers(eg 'set-cookie').

Pass a header object to `customHeaders` to tell Flareact to add those headers:

```js
export async function getEdgeProps() {
const data = await someExpensiveDataRequest();

return {
props: {
data,
},
customHeaders: {'set-cookie': 'cookie=monster; Expires=Wed, 21 Oct 2025 07:28:00 GMT'},
};
}
```
2 changes: 1 addition & 1 deletion docs/dynamic-routes.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ The params passed to your `getEdgeProps` function will contain each dynamic path
Dynamic routes can be extended to catch all paths by adding three dots `(...)` inside the brackets. For example:

```
/pages/posts/[..slug].js
/pages/posts/[...slug].js
```

`/pages/post/[...slug].js` matches `/pages/post/a`, but also `/pages/post/a/b`, `/pages/post/a/b/c` and so on.
Expand Down
24 changes: 24 additions & 0 deletions docs/flareact-link.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,27 @@ export default function Index() {
);
}
```

## Scroll

The default behaviour of the Link component is to scroll to the top of the page.
When there's a hash defined, it will scroll to the specific ID.

This feature is useful for a layered component where each tab needs to update the route.
By default, the scroll would go to the top of the page, but the correct behaviour is to update the route and change the tab's content.

You can disable this behaviour by passing a `false` value to `scroll`:

```js
import Link from "flareact/link";

export default function Index() {
return (
<div>
<Link href="/about" scroll={false}>
<a>Change route without scrolling top</a>
</Link>
</div>
);
}
```
6 changes: 6 additions & 0 deletions docs/flareact-router.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,11 @@ export default function Index() {

// Navigate to the dynamic route /posts/[slug] using `href`, `as`
router.push("/posts/[slug]", "/posts/my-first-post");

// Navigate back in history
router.back();

// Reload the current URL
router.reload();
}
```
3 changes: 2 additions & 1 deletion docs/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,5 +98,6 @@ CF_ACCOUNT_ID=youraccountid
Or pass it to `yarn dev` as an environment variable:

```bash
CF_ACCOUNT_ID=youraccountid yarn dev
CF_ACCOUNT_ID=youraccountid
yarn dev
```
4 changes: 2 additions & 2 deletions src/link.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export default function Link(props) {
const [childElm, setChildElm] = useState();
const child = Children.only(props.children);

const { href, as } = props;
const { href, as, scroll = true } = props;

const shouldPrefetch = props.prefetch !== false;

Expand Down Expand Up @@ -54,7 +54,7 @@ export default function Link(props) {

e.preventDefault();

router.push(href, as);
router.push(href, as, scroll);
}

const childProps = {
Expand Down
32 changes: 24 additions & 8 deletions src/router.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, { useContext, useState, useEffect, useMemo } from "react";
import { extractDynamicParams } from "./utils";
import React, { useContext, useEffect, useMemo, useState } from "react";

import { DYNAMIC_PAGE } from "./worker/pages";
import { extractDynamicParams } from "./utils";

const RouterContext = React.createContext();

Expand Down Expand Up @@ -45,17 +46,17 @@ export function RouterProvider({
}, [protocol, host, route.asPath, params]);

useEffect(() => {
// On initial page load, replace history state with format expected by router
// On initial page load, replace history state with format expected by router
window.history.replaceState(route, null, route.asPath);
}, [])

useEffect(() => {
async function loadNewPage() {
const { href, asPath } = route;
const { href, asPath, scroll } = route;
const pagePath = normalizePathname(href);
const normalizedAsPath = normalizePathname(asPath);

if (!pageCache[normalizedAsPath] || hasPagePropsExpired(pageCache[normalizedAsPath].expiry)) {
if ( !pageCache[normalizedAsPath] || hasPagePropsExpired(pageCache[normalizedAsPath].expiry)) {
const page = await pageLoader.loadPage(pagePath);
const { pageProps } = await pageLoader.loadPageProps(normalizedAsPath);
const revalidateSeconds = getRevalidateValue(pageProps);
Expand All @@ -69,7 +70,9 @@ export function RouterProvider({
}

setComponent(pageCache[normalizedAsPath]);
setTimeout(() => scrollToHash(asPath), 0);
if (scroll) {
setTimeout(() => scrollToHash(asPath), 0);
}
}

if (initialPath === route.asPath) {
Expand All @@ -83,7 +86,7 @@ export function RouterProvider({
if (seconds === null) {
return null;
}

return Date.now() + (seconds * 1000);
}

Expand All @@ -107,12 +110,13 @@ export function RouterProvider({
return pageProps.revalidate;
}

function push(href, as) {
function push(href, as, scroll) {
const asPath = as || href;

setRoute({
href,
asPath,
scroll
});

// Blank this out so any return trips to the original component re-fetches props.
Expand All @@ -121,6 +125,16 @@ export function RouterProvider({
window.history.pushState({ href, asPath }, null, asPath);
}

// Navigate back in history
function back() {
window.history.back()
}

// Reload the current URL
function reload() {
window.location.reload()
}

function prefetch(href, as, { priority } = {}) {
if (process.env.NODE_ENV !== "production") {
return;
Expand Down Expand Up @@ -191,6 +205,8 @@ export function RouterProvider({
pathname: route.href,
asPath: route.asPath,
push,
back,
reload,
prefetch,
query,
};
Expand Down
8 changes: 7 additions & 1 deletion src/worker/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,15 @@ export async function handleRequest(event, context, fallback) {
statusCode = 404;
}

let headers = { "content-type": "text/html" }

if (typeof props.customHeaders !== "undefined") {
headers = {...headers, ...props.customHeaders};
}

return new Response(html, {
status: statusCode,
headers: { "content-type": "text/html" },
headers: headers,
});
}
);
Expand Down
3 changes: 2 additions & 1 deletion src/worker/pages.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,11 +135,12 @@ export async function getPageProps(page, query, event) {
};

if (fetcher) {
const { props, notFound, revalidate } = await fetcher({ params, query: queryObject, event });
const { props, notFound, customHeaders, revalidate } = await fetcher({ params, query: queryObject, event });

pageProps = {
...props,
notFound,
customHeaders,
revalidate,
};
}
Expand Down
27 changes: 18 additions & 9 deletions src/worker/worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,28 @@ export async function handleEvent(event, context, DEBUG) {

return await getAssetFromKV(event, options);
} catch (e) {
// if an error is thrown try to serve the asset at 404.html
// if an error is thrown try to serve 404 response
if (!DEBUG) {
try {
let notFoundResponse = await getAssetFromKV(event, {
mapRequestToAsset: (req) =>
new Request(`${new URL(req.url).origin}/404.html`, req),
});
// try serving 404.js route
const newEvent = {};
newEvent.request = new Request(
`${new URL(event.request.url).origin}/404`,
new Request(event.request)
);
return await handleRequest(newEvent, context, async () => {
//no 404.js, try 404.html
let notFoundResponse = await getAssetFromKV(event, {
mapRequestToAsset: (req) =>
new Request(`${new URL(req.url).origin}/404.html`, req),
});

return new Response(notFoundResponse.body, {
...notFoundResponse,
status: 404,
return new Response(notFoundResponse.body, {
...notFoundResponse,
status: 404,
});
});
} catch (e) {}
} catch (e) { }
}

return new Response(e.message || e.toString(), { status: 500 });
Expand Down

0 comments on commit 6416b67

Please sign in to comment.