Skip to content

Commit 1f3e7cd

Browse files
author
Dimitri POSTOLOV
authoredSep 7, 2023
[v3] remove __nextra_internal__.refreshListeners (no longer needed since we insert toc as esm node in remark plugin) (#2267)

35 files changed

+88
-160
lines changed
 

‎.changeset/mean-countries-impress.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'nextra': patch
3+
---
4+
5+
fix `pageProps` for NextraLayout

‎.changeset/shy-seas-allow.md

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
'nextra': major
3+
---
4+
5+
- remove `__nextraPageOptions.hot`
6+
7+
- remove `__nextraPageOptions.pageOptsChecksum`
8+
9+
- remove `__nextra_internal__.refreshListeners` (no longer needed since we insert toc as esm node in remark plugin)
10+
11+
- remove `hashFnv32a`

‎examples/swr-site/pages/en/docs/advanced/cache.mdx

+1-1
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ When nested, SWR hooks will use the upper-level cache provider. If there is no
7575
upper-level cache provider, it fallbacks to the default cache provider, which is
7676
an empty `Map`.
7777

78-
<Callout emoji="⚠️">
78+
<Callout type='warning'>
7979
If a cache provider is used, the global `mutate` will **not** work for SWR hooks under that `<SWRConfig>` boundary. Please use [this](#access-current-cache-provider) instead.
8080
</Callout>
8181

‎examples/swr-site/pages/en/docs/arguments.mdx

+1-1
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,6 @@ object too:
6161
const { data: orders } = useSWR({ url: '/api/orders', args: user }, fetcher)
6262
```
6363

64-
<Callout emoji="⚠️">
64+
<Callout type='warning'>
6565
In older versions (< 1.1.0), SWR **shallowly** compares the arguments on every render, and triggers revalidation if any of them has changed.
6666
</Callout>

‎examples/swr-site/pages/en/docs/data-fetching.mdx

+3-3
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ The returned value will be passed as `data`, and if it throws, it will be caught
1313
as `error`.
1414

1515
<Callout>
16-
Note that <code>fetcher</code> can be omitted from the parameters if it's{' '}
17-
[provided globally](/docs/global-configuration).
16+
Note that `fetcher` can be omitted from the parameters if it's [provided
17+
globally](/docs/global-configuration).
1818
</Callout>
1919

2020
## Fetch
@@ -34,7 +34,7 @@ function App() {
3434
```
3535

3636
<Callout>
37-
If you are using <strong>Next.js</strong>, you don't need to import this
37+
If you are using **Next.js**, you don't need to import this
3838
polyfill:
3939

4040
[New Built-In Polyfills: fetch(), URL, and Object.assign](https://nextjs.org/blog/next-9-1-7#new-built-in-polyfills-fetch-url-and-objectassign)

‎examples/swr-site/pages/en/docs/error-handling.mdx

+2-3
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,8 @@ const { data, error } = useSWR('/api/user', fetcher)
4949
```
5050

5151
<Callout>
52-
Note that <code>data</code> and <code>error</code> can exist at the same time.
53-
So the UI can display the existing data, while knowing the upcoming request
54-
has failed.
52+
Note that `data` and `error` can exist at the same time. So the UI can display
53+
the existing data, while knowing the upcoming request has failed.
5554
</Callout>
5655

5756
[Here](/examples/error-handling) we have an example.

‎examples/swr-site/pages/en/docs/middleware.mdx

+1-1
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,7 @@ const { data, isLagging, resetLaggy } = useSWR(key, fetcher, { use: [laggy] })
184184
automatically.
185185
</Callout>
186186

187-
<Callout emoji="⚠️">
187+
<Callout type='warning'>
188188
In older versions (< 1.1.0), SWR **shallowly** compares the arguments on every render, and triggers revalidation if any of them has changed.
189189
If you are passing serializable objects as the key. You can serialize object keys to ensure its stability, a simple middleware can help:
190190
</Callout>

‎examples/swr-site/pages/en/docs/options.mdx

+2-2
Original file line numberDiff line numberDiff line change
@@ -72,8 +72,8 @@ const { data, error, isValidating, mutate } = useSWR(key, fetcher, options)
7272
- `use`: array of middleware functions [(details)](/docs/middleware)
7373

7474
<Callout>
75-
When under a slow network (2G, {'<='} 70Kbps), <code>errorRetryInterval</code>{' '}
76-
will be 10s, and <code>loadingTimeout</code> will be 5s by default.
75+
When under a slow network (2G, {'<='} 70Kbps), `errorRetryInterval` will be
76+
10s, and `loadingTimeout` will be 5s by default.
7777
</Callout>
7878

7979
You can also use [global configuration](/docs/global-configuration) to provide

‎examples/swr-site/pages/en/docs/pagination.mdx

+6-5
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@ import { Callout } from 'nextra/components'
33
# Pagination
44

55
<Callout emoji="">
6-
Please update to the latest version (≥ 0.3.0) to use this API. The previous{' '}
7-
<code>useSWRPages</code> API is now deprecated.
6+
Please update to the latest version (≥ 0.3.0) to use this API. The previous
7+
`useSWRPages` API is now deprecated.
88
</Callout>
99

1010
SWR provides a dedicated API `useSWRInfinite` to support common UI patterns such
@@ -212,11 +212,12 @@ React state.
212212
In infinite loading, one _page_ is one request, and our goal is to fetch
213213
multiple pages and render them.
214214
215-
<Callout emoji="⚠️">
215+
<Callout type='warning'>
216216
If you are using SWR 0.x versions, `useSWRInfinite` needs to be imported from
217217
`swr`:
218-
<br />
219-
`import {useSWRInfinite} from 'swr'`
218+
219+
`import {useSWRInfinite} from 'swr'`
220+
220221
</Callout>
221222
222223
### API

‎examples/swr-site/pages/en/docs/suspense.mdx

+4-3
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,12 @@ import { Callout } from 'nextra/components'
33
# Suspense
44

55
<Callout emoji="🚨" type="error">
6-
Suspense is currently an <strong>experimental</strong> feature of React. These
6+
Suspense is currently an **experimental** feature of React. These
77
APIs may change significantly and without a warning before they become a part
88
of React.
9-
<br />
10-
[More information](https://reactjs.org/docs/concurrent-mode-suspense.html)
9+
10+
[More information](https://reactjs.org/docs/concurrent-mode-suspense.html)
11+
1112
</Callout>
1213

1314
<Callout>Note that React Suspense is not yet supported in SSR mode.</Callout>

‎examples/swr-site/pages/es/docs/arguments.mdx

+1-1
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,6 @@ object too:
6262
const { data: orders } = useSWR({ url: '/api/orders', args: user }, fetcher)
6363
```
6464

65-
<Callout emoji="⚠️">
65+
<Callout type='warning'>
6666
In older versions (< 1.1.0), SWR **shallowly** compares the arguments on every render, and triggers revalidation if any of them has changed.
6767
</Callout>

‎examples/swr-site/pages/es/docs/data-fetching.mdx

+3-3
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ El valor devuelto será pasado como `data`, y si lanza, será capturado como
1313
`error`.
1414

1515
<Callout>
16-
Tenga en cuenta que el <code>fetcher</code> puede ser omitido de los
17-
parámetros si se [proporciona globalmente](/docs/global-configuration).
16+
Tenga en cuenta que el `fetcher` puede ser omitido de los parámetros si se
17+
[proporciona globalmente](/docs/global-configuration).
1818
</Callout>
1919

2020
## Fetch
@@ -34,7 +34,7 @@ function App() {
3434
```
3535

3636
<Callout>
37-
Si estás usando <strong>Next.js</strong>, no necesita importar este polyfill:
37+
Si estás usando **Next.js**, no necesita importar este polyfill:
3838

3939
[Nuevos Polyfills Incorporados: fetch(), URL, y Object.assign](https://nextjs.org/blog/next-9-1-7#new-built-in-polyfills-fetch-url-and-objectassign)
4040

‎examples/swr-site/pages/es/docs/pagination.mdx

+5-4
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { Callout } from 'nextra/components'
44

55
<Callout emoji="">
66
Por favor, actualice a la última versión (≥ 0.3.0) para utilizar esta API. La
7-
anterior API <code>useSWRPages</code> ha quedado obsoleta.
7+
anterior API `useSWRPages` ha quedado obsoleta.
88
</Callout>
99

1010
SWR proporciona una API dedicada `useSWRInfinite` para admitir patrones de UI
@@ -215,11 +215,12 @@ como un React state.
215215
En la carga infinita, una _page_ es una petición, y nuestro objetivo es obtener
216216
varias páginas y renderizarlas.
217217
218-
<Callout emoji="⚠️">
218+
<Callout type='warning'>
219219
If you are using SWR 0.x versions, `useSWRInfinite` needs to be imported from
220220
`swr`:
221-
<br />
222-
`import {useSWRInfinite} from 'swr'`
221+
222+
`import {useSWRInfinite} from 'swr'`
223+
223224
</Callout>
224225
225226
### API

‎examples/swr-site/pages/es/docs/suspense.mdx

+4-3
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,12 @@ import { Callout } from 'nextra/components'
33
# Suspense
44

55
<Callout emoji="🚨" type="error">
6-
Suspense es actualmente una característica <strong>experimental</strong> de
6+
Suspense es actualmente una característica **experimental** de
77
React. Estas APIs pueden cambiar significativamente y sin previo aviso antes
88
de que se conviertan en parte de React.
9-
<br />
10-
[Más información](https://reactjs.org/docs/concurrent-mode-suspense.html)
9+
10+
[Más información](https://reactjs.org/docs/concurrent-mode-suspense.html)
11+
1112
</Callout>
1213

1314
<Callout>

‎examples/swr-site/pages/es/index.mdx

+4-5
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,10 @@ devolver primero los datos en caché (obsoletos), luego envíe la solicitud de
1717
recuperación (revalidación), y finalmente entrege los datos actualizados.
1818

1919
<Callout emoji="">
20-
Con SWR, el componente obtendrá <strong>constante</strong> y{' '}
21-
<strong>automáticamente</strong> el último flujo de datos.
22-
<br />Y la interfaz de usuario será siempre <strong>rápida</strong> y <strong>
23-
reactiva
24-
</strong>.
20+
Con SWR, el componente obtendrá **constante** y **automáticamente** el último flujo de datos.
21+
22+
Y la interfaz de usuario será siempre **rápida** y **reactiva**.
23+
2524
</Callout>
2625

2726
<div className="mb-20 mt-16 text-center">

‎examples/swr-site/pages/ru/docs/advanced/cache.mdx

+6-5
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,14 @@ import { Callout } from 'nextra/components'
66
Обновитесь до последней версии (≥ 1.0.0), чтобы использовать этот функционал.
77
</Callout>
88

9-
<Callout emoji="⚠️">
9+
<Callout type='warning'>
1010
В большинстве случаев вы не должны напрямую _писать_ в кеш, поскольку это
1111
может вызвать неопределенное поведение SWR. Если вам нужно вручную изменить
1212
ключ, рассмотрите возможность использования API SWR.
13-
<br />
14-
См. также: [Мутация](/docs/mutation), [Сброс кеша между
15-
тестами](#сброс-кеша-между-тестами).
13+
14+
См. также: [Мутация](/docs/mutation),
15+
[Сброс кеша между тестами](#сброс-кеша-между-тестами).
16+
1617
</Callout>
1718

1819
По умолчанию SWR использует глобальный кеш для хранения и обмена данными между
@@ -78,7 +79,7 @@ import { Cache } from '@components/diagrams/cache'
7879
Если нет провайдера кеша верхнего уровня, он возвращается к провайдеру кэша по
7980
умолчанию, который является пустым `Map`.
8081

81-
<Callout emoji="⚠️">
82+
<Callout type='warning'>
8283
Если используется провайдер кеша, глобальный `mutate` **не** будет работать для хуков SWR в пределе
8384
этого `<SWRConfig>`. Пожалуйста, используйте [это](#доступ-к-текущему-провайдеру-кеша) взамен.
8485
</Callout>

‎examples/swr-site/pages/ru/docs/arguments.mdx

+1-1
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,6 @@ object too:
6161
const { data: orders } = useSWR({ url: '/api/orders', args: user }, fetcher)
6262
```
6363

64-
<Callout emoji="⚠️">
64+
<Callout type='warning'>
6565
In older versions (< 1.1.0), SWR **shallowly** compares the arguments on every render, and triggers revalidation if any of them has changed.
6666
</Callout>

‎examples/swr-site/pages/ru/docs/data-fetching.mdx

+3-3
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ const { data, error } = useSWR(key, fetcher)
1313
будет перехвачено как `error`.
1414

1515
<Callout>
16-
Обратите внимание, что <code>fetcher</code> можно не указывать в параметрах,
17-
если он [предоставляется глобально](/docs/global-configuration).
16+
Обратите внимание, что `fetcher` можно не указывать в параметрах, если он
17+
[предоставляется глобально](/docs/global-configuration).
1818
</Callout>
1919

2020
## Выборка (Fetch)
@@ -34,7 +34,7 @@ function App() {
3434
```
3535

3636
<Callout>
37-
Если вы используете <strong>Next.js</strong>, вам не нужно импортировать этот
37+
Если вы используете **Next.js**, вам не нужно импортировать этот
3838
полифил:
3939

4040
[Новые встроенные полифилы: fetch(), URL, и Object.assign](https://nextjs.org/blog/next-9-1-7#new-built-in-polyfills-fetch-url-and-objectassign)

‎examples/swr-site/pages/ru/docs/error-handling.mdx

+3-3
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,9 @@ const { data, error } = useSWR('/api/user', fetcher)
5050
```
5151

5252
<Callout>
53-
Обратите внимание, что <code>data</code> и <code>error</code> могут
54-
существовать одновременно. Таким образом, пользовательский интерфейс может
55-
отображать существующие данные, зная, что предстоящий запрос потерпел неудачу.
53+
Обратите внимание, что `data` и `error` могут существовать одновременно. Таким
54+
образом, пользовательский интерфейс может отображать существующие данные,
55+
зная, что предстоящий запрос потерпел неудачу.
5656
</Callout>
5757

5858
[Здесь](/examples/error-handling) у нас есть пример.

‎examples/swr-site/pages/ru/docs/middleware.mdx

+1-1
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ const { data, isLagging, resetLaggy } = useSWR(key, fetcher, { use: [laggy] })
187187
automatically.
188188
</Callout>
189189

190-
<Callout emoji="⚠️">
190+
<Callout type='warning'>
191191
In older versions (< 1.1.0), SWR **shallowly** compares the arguments on every render, and triggers revalidation if any of them has changed.
192192
If you are passing serializable objects as the key. You can serialize object keys to ensure its stability, a simple middleware can help:
193193
</Callout>

‎examples/swr-site/pages/ru/docs/options.mdx

+2-2
Original file line numberDiff line numberDiff line change
@@ -76,8 +76,8 @@ const { data, error, isValidating, mutate } = useSWR(key, fetcher, options)
7676
- `use`: массив middleware-функций [(подробнее)](/docs/middleware)
7777

7878
<Callout>
79-
В медленной сети (2G, {'<='} 70 Кбит/с), <code>errorRetryInterval</code> будет
80-
10 секунд, а&nbsp;<code>loadingTimeout</code> будет по умолчанию 5 секунд.
79+
В медленной сети (2G, {'<='} 70 Кбит/с), `errorRetryInterval` будет 10 секунд,
80+
а&nbsp;`loadingTimeout` будет по умолчанию 5 секунд.
8181
</Callout>
8282

8383
Вы также можете использовать

‎examples/swr-site/pages/ru/docs/pagination.mdx

+5-4
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { Callout } from 'nextra/components'
44

55
<Callout emoji="">
66
Пожалуйста, обновитесь до последней версии (≥ 0.3.0), чтобы использовать этот
7-
API. Предыдущий API <code>useSWRPages</code> является устаревшим.
7+
API. Предыдущий API `useSWRPages` является устаревшим.
88
</Callout>
99

1010
SWR предоставляет специальный API `useSWRInfinite` для поддержки общепринятых UI
@@ -216,11 +216,12 @@ const { data, error, isValidating, mutate, size, setSize } = useSWRInfinite(
216216
При бесконечной загрузке одна _страница_ — это один запрос, и наша цель —
217217
получить несколько страниц и отобразить их.
218218
219-
<Callout emoji="⚠️">
219+
<Callout type='warning'>
220220
Если вы используете версии SWR 0.x, `useSWRInfinite` необходимо импортировать
221221
из `swr`:
222-
<br />
223-
`import {useSWRInfinite} from 'swr'`
222+
223+
`import {useSWRInfinite} from 'swr'`
224+
224225
</Callout>
225226
226227
### API

‎examples/swr-site/pages/ru/docs/suspense.mdx

+4-4
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,11 @@ import { Callout } from 'nextra/components'
33
# Задержка (Suspense)
44

55
<Callout emoji="🚨" type="error">
6-
Задержка (Suspense) в настоящее время является{' '}
7-
<strong>экспериментальной</strong> функцией React. Эти API могут значительно
6+
Задержка (Suspense) в настоящее время является **экспериментальной** функцией React. Эти API могут значительно
87
измениться без предупреждения, прежде чем станут частью React.
9-
<br />
10-
[Подробнее](https://reactjs.org/docs/concurrent-mode-suspense.html)
8+
9+
[Подробнее](https://reactjs.org/docs/concurrent-mode-suspense.html)
10+
1111
</Callout>
1212

1313
<Callout>

‎examples/swr-site/pages/ru/index.mdx

+4-5
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,10 @@ HTTP-кеша, популяризированная
1717
(ревалидация), и в итоге возвращает актуальные данные.
1818

1919
<Callout emoji="">
20-
С SWR, компоненты получат поток <strong>постоянно</strong> и{' '}
21-
<strong>автоматически</strong> обновляющихся данных.
22-
<br />И пользовательский интерфейс всегда будет <strong>быстрым</strong> и <strong>
23-
реактивным
24-
</strong>.
20+
С SWR, компоненты получат поток **постоянно** и **автоматически** обновляющихся данных.
21+
22+
И пользовательский интерфейс всегда будет **быстрым** и **реактивным**.
23+
2524
</Callout>
2625

2726
<div className="mb-20 mt-16 text-center">

‎packages/nextra/__test__/loader.test.ts

-9
Original file line numberDiff line numberDiff line change
@@ -43,21 +43,12 @@ describe('tree shaking', async () => {
4343
it('should not include `pageOpts.pageMap`', () => {
4444
expect(testPage.includes('pageMap:')).toBe(true)
4545
})
46-
it('should not include default `pageOpts.frontMatter: {}`', () => {
47-
expect(testPage.includes('frontMatter:')).toBe(true)
48-
})
4946
it('should not include `pageOpts.search`', () => {
5047
expect(testPage.includes('search:')).toBe(false)
5148
})
5249
it('should not include `themeConfig`', () => {
5350
expect(testPage.includes('themeConfig:')).toBe(false)
5451
})
55-
it('should not include `hot`', () => {
56-
expect(testPage.includes('hot:')).toBe(false)
57-
})
58-
it('should not include `pageOptsChecksum`', () => {
59-
expect(testPage.includes('pageOptsChecksum:')).toBe(false)
60-
})
6152
it('should not include `dynamicMetaModules`', () => {
6253
expect(testPage.includes('dynamicMetaModules:')).toBe(false)
6354
})

‎packages/nextra/package.json

-1
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,6 @@
157157
"@types/react": "^18.2.21",
158158
"@types/react-dom": "^18.2.7",
159159
"@types/webpack": "^5.28.2",
160-
"@types/webpack-env": "^1.18.1",
161160
"@vitejs/plugin-react": "^3.0.1",
162161
"fast-glob": "^3.2.12",
163162
"next": "^13.4.19",

‎packages/nextra/src/compile.ts

+1-3
Original file line numberDiff line numberDiff line change
@@ -183,9 +183,7 @@ export async function compileMdx(
183183
...(hasJsxInH1 && { hasJsxInH1 }),
184184
...(readingTime && { readingTime }),
185185
...(searchIndexKey !== null && { searchIndexKey, structurizedData }),
186-
...(isRemoteContent && {
187-
headings: vFile.data.headings
188-
}),
186+
...(isRemoteContent && { headings: vFile.data.headings }),
189187
frontMatter
190188
}
191189
} catch (err) {

‎packages/nextra/src/layout.tsx

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ export default function Nextra({
2828
}
2929
}
3030
return (
31-
<Layout themeConfig={themeConfig} pageOpts={pageOpts}>
31+
<Layout themeConfig={themeConfig} pageOpts={pageOpts} pageProps={props}>
3232
<SSGContext.Provider value={props}>
3333
<Content />
3434
</SSGContext.Provider>

‎packages/nextra/src/loader.ts

+1-9
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
import { PAGES_DIR } from './file-system'
1313
import { collectMdx } from './plugin'
1414
import type { FileMap, LoaderOptions, MdxPath, PageOpts } from './types'
15-
import { hashFnv32a, logger, pageTitleFromFilename } from './utils'
15+
import { logger, pageTitleFromFilename } from './utils'
1616

1717
const initGitRepo = (async () => {
1818
const IS_WEB_CONTAINER = !!process.versions.webcontainer
@@ -258,9 +258,6 @@ ${themeConfigImport && '__nextra_internal__.themeConfig = __themeConfig'}`
258258
const stringifiedPageOpts =
259259
JSON.stringify(pageOpts).slice(0, -1) +
260260
',headings:__toc,pageMap:__nextraPageMap,frontMatter}'
261-
const stringifiedChecksum = IS_PRODUCTION
262-
? "''"
263-
: JSON.stringify(hashFnv32a(stringifiedPageOpts))
264261

265262
const lastIndexOfFooter = finalResult.lastIndexOf(FOOTER_TO_REMOVE)
266263
const mdxContent =
@@ -279,11 +276,6 @@ const __nextraPageOptions = {
279276
route: '${route}',
280277
pageOpts: ${stringifiedPageOpts}
281278
}
282-
283-
if (process.env.NODE_ENV !== 'production') {
284-
__nextraPageOptions.hot = module.hot
285-
__nextraPageOptions.pageOptsChecksum = ${stringifiedChecksum}
286-
}
287279
if (typeof window === 'undefined') {
288280
__nextraPageOptions.dynamicMetaModules = dynamicMetaModules
289281
}

‎packages/nextra/src/setup-page.ts

-21
Original file line numberDiff line numberDiff line change
@@ -98,15 +98,11 @@ let cachedResolvedPageMap: PageMapItem[]
9898
export function setupNextraPage({
9999
pageOpts,
100100
MDXContent,
101-
hot,
102-
pageOptsChecksum,
103101
dynamicMetaModules = [],
104102
route
105103
}: {
106104
pageOpts: PageOpts
107105
MDXContent: FC
108-
hot?: __WebpackModuleApi.Hot
109-
pageOptsChecksum?: string
110106
dynamicMetaModules?: [() => any, DynamicMetaDescriptor][]
111107
route: string
112108
}) {
@@ -138,26 +134,9 @@ export function setupNextraPage({
138134
]
139135
__nextra_internal__.route = route
140136
__nextra_internal__.pageMap = pageOpts.pageMap
141-
142-
pageOpts.frontMatter ||= {}
143137
__nextra_internal__.context[route] = {
144138
Content: MDXContent,
145139
pageOpts
146140
}
147-
148-
if (process.env.NODE_ENV !== 'production' && hot) {
149-
__nextra_internal__.refreshListeners ||= Object.create(null)
150-
const checksum = pageOptsChecksum
151-
hot.data ||= Object.create(null)
152-
if (hot.data.prevPageOptsChecksum !== checksum) {
153-
const listeners = __nextra_internal__.refreshListeners[route] || []
154-
for (const listener of listeners) {
155-
listener()
156-
}
157-
}
158-
hot.dispose(data => {
159-
data.prevPageOptsChecksum = checksum
160-
})
161-
}
162141
return NextraLayout
163142
}

‎packages/nextra/src/types.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,7 @@ export type ThemeConfig = any | null
109109

110110
export type NextraThemeLayoutProps = {
111111
pageOpts: PageOpts
112+
pageProps: any
112113
themeConfig: ThemeConfig
113114
children: ReactNode
114115
}
@@ -118,7 +119,6 @@ export type NextraInternalGlobal = typeof globalThis & {
118119
pageMap: PageMapItem[]
119120
route: string
120121
context: Record<string, { Content: FC; pageOpts: PageOpts }>
121-
refreshListeners: Record<string, (() => void)[]>
122122
Layout: FC<NextraThemeLayoutProps>
123123
themeConfig?: ThemeConfig
124124
}

‎packages/nextra/src/use-internals.ts

+1-23
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import { useRouter } from 'next/router'
2-
import { useEffect, useState } from 'react'
32
import { NEXTRA_INTERNAL } from './constants'
43
import type { NextraInternalGlobal } from './types'
54

@@ -12,28 +11,7 @@ export function useInternals() {
1211
NEXTRA_INTERNAL
1312
]
1413
const { route } = useRouter()
15-
console.log({route})
16-
const rerender = useState({})[1]
17-
18-
// The HMR handling logic is not needed for production builds, the condition
19-
// should be removed after compilation, and it's fine to put the effect under
20-
// if, because hooks' order is still stable.
21-
if (process.env.NODE_ENV !== 'production') {
22-
// eslint-disable-next-line react-hooks/rules-of-hooks
23-
useEffect(() => {
24-
const trigger = () => rerender({})
25-
26-
const listeners = __nextra_internal__.refreshListeners
27-
28-
listeners[route] ||= []
29-
listeners[route].push(trigger)
30-
31-
return () => {
32-
listeners[route].splice(listeners[route].indexOf(trigger), 1)
33-
}
34-
}, [route, __nextra_internal__.refreshListeners, rerender])
35-
}
36-
14+
console.log({ route })
3715
const context = __nextra_internal__.context[route]
3816

3917
if (!context) {

‎packages/nextra/src/utils.ts

-21
Original file line numberDiff line numberDiff line change
@@ -59,27 +59,6 @@ export function isSerializable(o: any): boolean {
5959
}
6060
}
6161

62-
/**
63-
* Calculate a 32 bit FNV-1a hash
64-
* Found here: https://gist.github.com/vaiorabbit/5657561
65-
* Ref.: http://isthe.com/chongo/tech/comp/fnv/
66-
*
67-
* @param {string} str the input value
68-
* @param {number} [seed] optionally pass the hash of the previous chunk
69-
* @returns {string}
70-
*/
71-
export function hashFnv32a(str: string, seed = 0x811c9dc5): string {
72-
let hval = seed
73-
74-
for (let i = 0; i < str.length; i++) {
75-
hval ^= str.charCodeAt(i)
76-
hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24)
77-
}
78-
79-
// Convert to 8 digit hex string
80-
return ('0000000' + (hval >>> 0).toString(16)).substring(-8)
81-
}
82-
8362
export function getDefault<T>(module: T & { default?: T }): T {
8463
return module.default || module
8564
}

‎packages/nextra/tsconfig.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
"jsx": "react-jsx",
1212
"lib": ["es2022", "dom"],
1313
"moduleResolution": "node",
14-
"types": ["vitest/globals", "webpack-env"],
14+
"types": ["vitest/globals"],
1515
"resolveJsonModule": true,
1616
"paths": {
1717
"unified": ["./node_modules/unified"]

‎pnpm-lock.yaml

-7
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)
Please sign in to comment.