Skip to content

Commit

Permalink
Merge branch 'canary' into use-selected-segment-root
Browse files Browse the repository at this point in the history
  • Loading branch information
Hannes Bornö authored Nov 2, 2022
2 parents 0714625 + 85d5371 commit 619e801
Show file tree
Hide file tree
Showing 20 changed files with 1,426 additions and 220 deletions.
16 changes: 8 additions & 8 deletions docs/api-reference/next/font.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,14 +107,14 @@ For usage, review [Local Fonts](/docs/optimizing/fonts#local-fonts).

### `src`

The path of the font file as a string relative to the directory where the font loader function is called or to the `app` directory.
The path of the font file as a string relative to the directory where the font loader function is called or to the `pages` directory.

- Required

Examples are:

- `'./fonts/my-font.woff2'` where `my-font.woff2` is placed in a directory named `fonts` inside the `app` directory
- if the font loader function is called in `app/page.tsx` using `'../styles/fonts/my-font.ttf'`, then `my-font.ttf` is placed in `styles/fonts` at the root of the project
- `'./fonts/my-font.woff2'` where `my-font.woff2` is placed in a directory named `fonts` inside the `pages` directory
- if the font loader function is called in `pages/index.js` using `'../styles/fonts/my-font.ttf'`, then `my-font.ttf` is placed in `styles/fonts` at the root of the project

### `weight`

Expand Down Expand Up @@ -194,8 +194,8 @@ If you would like to set your styles in an external style sheet and specify addi

In addition to importing the font, also import the CSS file where the CSS variable is defined and set the variable option of the font loader object as follows:

```tsx
// app/page.tsx
```js
// pages/index.js
import { Inter } from '@next/font/google'
import styles from '../styles/component.module.css'

Expand All @@ -206,8 +206,8 @@ const inter = Inter({

To use the font, set the `className` of the parent container of the text you would like to style to the font loader's `variable` value and the `className` of the text to the `styles` property from the external CSS file.

```tsx
// app/page.tsx
```js
// pages/index.js
<main className={inter.variable}>
<p className={styles.text}>Hello World</p>
</main>
Expand Down Expand Up @@ -295,7 +295,7 @@ import { greatVibes, sourceCodePro400 } from '@/fonts';

<div class="card">
<a href="/docs/basic-features/font-optimization.md">
<b>Font Optmization</b>
<b>Font Optimization</b>
<small>Learn how to optimize fonts with the Font module.</small>
</a>
</div>
108 changes: 67 additions & 41 deletions docs/basic-features/font-optimization.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,49 +26,82 @@ Automatically self-host any Google Font. Fonts are included in the deployment an

Import the font you would like to use from `@next/font/google` as a function. We recommend using [**variable fonts**](https://fonts.google.com/variablefonts) for the best performance and flexibility.

```jsx
// app/layout.tsx
import { Inter } from '@next/font/google'
To use the font in all your pages, add it to [`_app.js` file](https://nextjs.org/docs/advanced-features/custom-app) under `/pages` as shown below:

```js:pages/_app.js
import { Inter } from '@next/font/google';

// If loading a variable font, you don't need to specify the font weight
const inter = Inter()

export default function RootLayout({
children,
}: {
children: React.ReactNode,
}) {
export default function MyApp({ Component, pageProps }) {
return (
<html lang="en" className={inter.className}>
<body>{children}</body>
</html>
<main className={inter.className}>
<Component {...pageProps} />
</main>
)
}
```

If you can't use a variable font, you will **need to specify a weight**:

```jsx
// app/layout.tsx
import { Roboto } from '@next/font/google'
```js:pages/_app.js
import { Roboto } from '@next/font/google';

const roboto = Roboto({
weight: '400',
})

export default function RootLayout({
children,
}: {
children: React.ReactNode,
}) {
export default function MyApp({ Component, pageProps }) {
return (
<main className={roboto.className}>
<Component {...pageProps} />
</main>
)
}
```

#### Apply the font in `<head>`

You can also use the font without a wrapper and `className` by injecting it inside the `<head>` as follows:

```js:pages/_app.js
import { Inter } from '@next/font/google';

const inter = Inter();

export default function MyApp({ Component, pageProps }) {
return (
<html lang="en" className={roboto.className}>
<body>{children}</body>
</html>
<>
<style jsx global>{`
html {
font-family: ${inter.style.fontFamily};
}
`}</style>
<Component {...pageProps} />
</>
)
}
```

#### Single page usage

To use the font on a single page, add it to the specific page as shown below:

```js:pages/index.js
import { Inter } from '@next/font/google';

const inter = Inter();

export default function Home() {
return (
<div className={inter.className}>
<p>Hello World</p>
</div>
);
}
```

#### Specifying a subset

Google Fonts are automatically [subset](https://fonts.google.com/knowledge/glossary/subsetting). This reduces the size of the font file and improves performance. You'll need to define which of these subsets you want to preload. Failing to specify any subsets while [`preload`](/docs/api-reference/next/font.md#preload) is true will result in a warning.
Expand All @@ -77,9 +110,8 @@ This can be done in 2 ways:

- On a font per font basis by adding it to the function call

```tsx
// app/layout.tsx
const inter = Inter({ subsets: ['latin'] })
```js:pages/_app.js
const inter = Inter({ subsets: ["latin"] });
```

- Globally for all your fonts in your `next.config.js`
Expand All @@ -103,22 +135,17 @@ View the [Font API Reference](/docs/api-reference/next/font.md#nextfontgoogle) f

Import `@next/font/local` and specify the `src` of your local font file. We recommend using [**variable fonts**](https://fonts.google.com/variablefonts) for the best performance and flexibility.

```jsx
/// app/layout.tsx
import localFont from '@next/font/local'
```js:pages/_app.js
import localFont from '@next/font/local';

// Font files can be colocated inside of `app`
const myFont = localFont({ src: './my-font.woff2' })
// Font files can be colocated inside of `pages`
const myFont = localFont({ src: './my-font.woff2' });

export default function RootLayout({
children,
}: {
children: React.ReactNode,
}) {
export default function MyApp({ Component, pageProps }) {
return (
<html lang="en" className={myFont.className}>
<body>{children}</body>
</html>
<main className={myFont.className}>
<Component {...pageProps} />
</main>
)
}
```
Expand All @@ -129,9 +156,8 @@ View the [Font API Reference](/docs/api-reference/next/font.md#nextfontlocal) fo

When a font function is called on a page of your site, it is not globally available and preloaded on all routes. Rather, the font is only preloaded on the related route/s based on the type of file where it is used:

- if it's a [unique page](https://beta.nextjs.org/docs/routing/pages-and-layouts#pages), it is preloaded on the unique route for that page
- if it's a [layout](https://beta.nextjs.org/docs/routing/pages-and-layouts#layouts), it is preloaded on all the routes wrapped by the layout
- if it's the [root layout](https://beta.nextjs.org/docs/routing/pages-and-layouts#root-layout-required), it is preloaded on all routes
- if it's a [unique page](/docs/basic-features/pages), it is preloaded on the unique route for that page
- if it's in the [custom App](/docs/advanced-features/custom-app), it is preloaded on all the routes of the site under `/pages`

## Reusing fonts

Expand Down
2 changes: 1 addition & 1 deletion docs/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
description: Get started with Next.js in the official documentation, and learn more about all our features!
---

> Next.js 13 has been [publicly released](https://nextjs.org/blog/next-13), [read the docs here](https://beta.nextjs.org/docs).
> Next.js 13 was recently released, [learn more](https://nextjs.org/blog/next-13) and see the [upgrade guide](https://nextjs.org/docs/upgrading#upgrading-from-12-to-13). Version 13 also introduces beta features like the [`app` directory](https://beta.nextjs.org/docs/app-directory-roadmap) that works alongside the `pages` directory (stable) for incremental adoption. You can continue using `pages` in Next.js 13, but if you want to try the new `app` features, [see the new beta docs](https://beta.nextjs.org/docs).
# Getting Started

Expand Down
2 changes: 1 addition & 1 deletion docs/upgrading.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ pnpm up next react react-dom eslint-config-next --latest

## Migrating shared features

Next.js 13 introduces a new [`app` directory](https://beta.nextjs.org/docs/routing/fundamentals) with new features and conventions. However, upgrading to Next.js 13 does **not** require using the new [`app` directory](https://beta.nextjs.org/docs/routing/fundamentals.md#the-app-directory).
Next.js 13 introduces a new [`app` directory](https://beta.nextjs.org/docs/routing/fundamentals) with new features and conventions. However, upgrading to Next.js 13 does **not** require using the new [`app` directory](https://beta.nextjs.org/docs/routing/fundamentals#the-app-directory).

You can continue using `pages` with new features that work in both directories, such as the updated [Image component](#image-component), [Link component](#link-component), [Script component](#script-component), and [Font optimization](#font-optimization).

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@
"selenium-webdriver": "4.0.0-beta.4",
"semver": "7.3.7",
"shell-quote": "1.7.3",
"styled-components": "5.3.3",
"styled-components": "6.0.0-beta.5",
"styled-jsx-plugin-postcss": "3.0.2",
"swr": "2.0.0-rc.0",
"tailwindcss": "1.1.3",
Expand Down
19 changes: 13 additions & 6 deletions packages/next/build/webpack/loaders/next-app-loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ export const FILE_TYPES = {
'not-found': 'not-found',
} as const

const PAGE_SEGMENT = 'page$'

// TODO-APP: check if this can be narrowed.
type ComponentModule = () => any
export type ComponentsType = {
Expand Down Expand Up @@ -59,10 +61,8 @@ async function createTreeCodeFromPath({
}

for (const [parallelKey, parallelSegment] of parallelSegments) {
const parallelSegmentPath = segmentPath + '/' + parallelSegment

if (parallelSegment === 'page') {
const matchedPagePath = `${appDirPrefix}${parallelSegmentPath}`
if (parallelSegment === PAGE_SEGMENT) {
const matchedPagePath = `${appDirPrefix}${segmentPath}/page`
const resolvedPagePath = await resolve(matchedPagePath)
if (resolvedPagePath) pages.push(resolvedPagePath)

Expand All @@ -73,6 +73,7 @@ async function createTreeCodeFromPath({
continue
}

const parallelSegmentPath = segmentPath + '/' + parallelSegment
const subtree = await createSubtreePropsFromSegmentPath([
...segments,
parallelSegment,
Expand Down Expand Up @@ -175,12 +176,18 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{
const matched: Record<string, string> = {}
for (const path of normalizedAppPaths) {
if (path.startsWith(pathname + '/')) {
const restPath = path.slice(pathname.length + 1)
const rest = path.slice(pathname.length + 1).split('/')

let matchedSegment = rest[0]
// It is the actual page, mark it sepcially.
if (rest.length === 1 && matchedSegment === 'page') {
matchedSegment = PAGE_SEGMENT
}

const matchedSegment = restPath.split('/')[0]
const matchedKey = matchedSegment.startsWith('@')
? matchedSegment.slice(1)
: 'children'

matched[matchedKey] = matchedSegment
}
}
Expand Down
47 changes: 36 additions & 11 deletions packages/next/server/node-web-streams-helper.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import type { FlightRouterState } from './app-render'
import { nonNullable } from '../lib/non-nullable'

const queueTask =
process.env.NEXT_RUNTIME === 'edge' ? globalThis.setTimeout : setImmediate

export type ReactReadableStream = ReadableStream<Uint8Array> & {
allReady?: Promise<void> | undefined
}
Expand Down Expand Up @@ -149,21 +152,43 @@ export function renderToInitialStream({
return ReactDOMServer.renderToReadableStream(element, streamOptions)
}

export function createHeadInjectionTransformStream(
inject: () => Promise<string>
function createHeadInsertionTransformStream(
insert: () => Promise<string>
): TransformStream<Uint8Array, Uint8Array> {
let injected = false
let inserted = false
let freezing = false

return new TransformStream({
async transform(chunk, controller) {
const content = decodeText(chunk)
let index
if (!injected && (index = content.indexOf('</head')) !== -1) {
injected = true
const injectedContent =
content.slice(0, index) + (await inject()) + content.slice(index)
controller.enqueue(encodeText(injectedContent))
// While react is flushing chunks, we don't apply insertions
if (freezing) {
controller.enqueue(chunk)
return
}

const insertion = await insert()
if (inserted) {
controller.enqueue(encodeText(insertion))
controller.enqueue(chunk)
freezing = true
} else {
const content = decodeText(chunk)
const index = content.indexOf('</head')
if (index !== -1) {
const insertedHeadContent =
content.slice(0, index) + insertion + content.slice(index)
controller.enqueue(encodeText(insertedHeadContent))
freezing = true
inserted = true
}
}

if (!inserted) {
controller.enqueue(chunk)
} else {
queueTask(() => {
freezing = false
})
}
},
})
Expand Down Expand Up @@ -333,7 +358,7 @@ export async function continueFromInitialStream(
suffixUnclosed != null ? createDeferredSuffixStream(suffixUnclosed) : null,
dataStream ? createInlineDataStream(dataStream) : null,
suffixUnclosed != null ? createSuffixStream(closeTag) : null,
createHeadInjectionTransformStream(async () => {
createHeadInsertionTransformStream(async () => {
// TODO-APP: Insert server side html to end of head in app layout rendering, to avoid
// hydration errors. Remove this once it's ready to be handled by react itself.
const serverInsertedHTML =
Expand Down
Loading

0 comments on commit 619e801

Please sign in to comment.