@rspress/core 2.1.2 → 2.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { useSearchParams } from '@rspress/core/runtime';
1
+ import { useLocation, useSearchParams } from '@rspress/core/runtime';
2
2
  import clsx from 'clsx';
3
3
  import {
4
4
  Children,
@@ -52,26 +52,28 @@ export interface PageTabsProps {
52
52
 
53
53
  function usePageTabs(id: string, children: ReactElement<PageTabProps>[]) {
54
54
  const [searchParams, setSearchParams] = useSearchParams();
55
+ const { search } = useLocation();
55
56
 
56
57
  const tabValues = useMemo(() => {
57
58
  return getTabValuesFromChildren(children);
58
59
  }, [children]);
59
60
 
60
61
  function navigateToTab(index: number) {
62
+ const nextSearchParams = new URLSearchParams(searchParams);
61
63
  if (index === 0) {
62
- searchParams.delete(id);
64
+ nextSearchParams.delete(id);
63
65
  } else {
64
- searchParams.set(id, String(index));
66
+ nextSearchParams.set(id, String(index));
65
67
  }
66
- setSearchParams(searchParams);
68
+ setSearchParams(nextSearchParams);
67
69
  }
68
70
 
69
71
  useEffect(() => {
70
- const currIndex = Number(searchParams.get(id) ?? '0');
72
+ const currIndex = Number(new URLSearchParams(search).get(id) ?? '0');
71
73
  if (!Number.isNaN(currIndex)) {
72
74
  document.body.dataset.pageTabsActiveIndex = currIndex.toString();
73
75
  }
74
- }, [searchParams]);
76
+ }, [id, search]);
75
77
 
76
78
  const injectScript = `(function () {
77
79
  var searchParams = new URLSearchParams(window.location.search);
@@ -88,8 +90,6 @@ function usePageTabs(id: string, children: ReactElement<PageTabProps>[]) {
88
90
  };
89
91
  }
90
92
 
91
- let renderCountForTocUpdate = 0;
92
-
93
93
  export const PageTabs = forwardRef(
94
94
  (props: PageTabsProps, ref: ForwardedRef<HTMLDivElement>): ReactElement => {
95
95
  const {
@@ -111,8 +111,6 @@ export const PageTabs = forwardRef(
111
111
  children,
112
112
  );
113
113
 
114
- renderCountForTocUpdate++;
115
-
116
114
  return (
117
115
  <>
118
116
  {/* First screen during SSR */}
@@ -159,14 +157,6 @@ export const PageTabs = forwardRef(
159
157
  })}
160
158
  </div>
161
159
  </div>
162
- {/*
163
- Render a hidden <h2> element to trigger a Table of Contents (TOC) update.
164
- This mechanism ensures that the TOC stays in sync with tab content changes,
165
- as some TOC generators rely on heading elements being present in the DOM.
166
- */}
167
- {renderCountForTocUpdate % 2 === 0 ? (
168
- <h2 style={{ display: 'none' }} />
169
- ) : null}
170
160
  </>
171
161
  );
172
162
  },
@@ -0,0 +1,91 @@
1
+ import { afterEach, describe, expect, it, rs } from '@rstest/core';
2
+ import { renderToMarkdownString } from 'react-render-to-markdown';
3
+ import { renderInlineMarkdown } from '../../logic/utils';
4
+ import { Prompt } from './index';
5
+
6
+ rs.mock('@rspress/core/runtime', () => ({
7
+ useI18n: () => (key: string) => key,
8
+ }));
9
+
10
+ rs.mock('@rspress/core/theme', () => ({ renderInlineMarkdown }));
11
+
12
+ const originalSsgMd = import.meta.env.SSG_MD;
13
+
14
+ afterEach(() => {
15
+ if (originalSsgMd === undefined) {
16
+ delete (import.meta.env as unknown as Record<string, unknown>).SSG_MD;
17
+ } else {
18
+ (import.meta.env as unknown as Record<string, unknown>).SSG_MD =
19
+ originalSsgMd;
20
+ }
21
+ });
22
+
23
+ describe('Prompt Markdown rendering', () => {
24
+ it('preserves prompt text in a code block and omits interactive controls', async () => {
25
+ (import.meta.env as unknown as Record<string, unknown>).SSG_MD = true;
26
+ const prompt =
27
+ 'Follow https://rspress.rs/guide/start/getting-started.md.\n\n1. Run `create rspress@latest`.\n2. Start the dev server.\n\n```sh\npnpm dev\n```';
28
+ const markdown = await renderToMarkdownString(
29
+ <Prompt
30
+ title="Start a Rspress project"
31
+ description="Send this to your **AI agent**."
32
+ prompt={prompt}
33
+ />,
34
+ );
35
+ expect(markdown).toMatchInlineSnapshot(`
36
+ "**Start a Rspress project**
37
+
38
+ Send this to your **AI agent**.
39
+
40
+
41
+ \`\`\`\`
42
+ <prompt>
43
+ Follow https://rspress.rs/guide/start/getting-started.md.
44
+
45
+ 1. Run \`create rspress@latest\`.
46
+ 2. Start the dev server.
47
+
48
+ \`\`\`sh
49
+ pnpm dev
50
+ \`\`\`
51
+ </prompt>
52
+ \`\`\`\`
53
+ "
54
+ `);
55
+ expect(markdown).toContain(`<prompt>\n${prompt}\n</prompt>`);
56
+ expect(markdown).toContain('Send this to your **AI agent**.');
57
+ expect(markdown).not.toContain('promptCopyText');
58
+ expect(markdown).not.toContain('For your Agent');
59
+ });
60
+
61
+ it('renders custom children as Markdown without a code block', async () => {
62
+ (import.meta.env as unknown as Record<string, unknown>).SSG_MD = true;
63
+ expect(
64
+ await renderToMarkdownString(
65
+ <Prompt custom eyebrow="Agent resources">
66
+ <h3>Get started</h3>
67
+ <p>
68
+ <a href="https://rspress.rs">Read the guide</a>
69
+ </p>
70
+ </Prompt>,
71
+ ),
72
+ ).toMatchInlineSnapshot(`
73
+ "**Agent resources**
74
+
75
+ ### Get started
76
+
77
+ [Read the guide](https://rspress.rs)
78
+
79
+ "
80
+ `);
81
+ });
82
+
83
+ it('uses the default title and omits absent content', async () => {
84
+ (import.meta.env as unknown as Record<string, unknown>).SSG_MD = true;
85
+ expect(await renderToMarkdownString(<Prompt />)).toMatchInlineSnapshot(`
86
+ "**Agent Prompt**
87
+
88
+ "
89
+ `);
90
+ });
91
+ });
@@ -329,6 +329,37 @@ function CopyablePrompt({
329
329
  }
330
330
 
331
331
  export function Prompt({ custom = false, ...props }: PromptProps) {
332
+ if (import.meta.env.SSG_MD) {
333
+ const {
334
+ children,
335
+ description,
336
+ eyebrow = 'For your Agent',
337
+ prompt,
338
+ title = 'Agent Prompt',
339
+ } = props;
340
+
341
+ if (custom) {
342
+ return (
343
+ <>
344
+ <p>
345
+ <strong>{eyebrow}</strong>
346
+ </p>
347
+ {children}
348
+ </>
349
+ );
350
+ }
351
+
352
+ return (
353
+ <>
354
+ <p>
355
+ <strong>{title}</strong>
356
+ </p>
357
+ {description ? <p>{description}</p> : null}
358
+ {prompt ? <pre>{`<prompt>\n${prompt}\n</prompt>`}</pre> : null}
359
+ </>
360
+ );
361
+ }
362
+
332
363
  return custom ? <CustomPrompt {...props} /> : <CopyablePrompt {...props} />;
333
364
  }
334
365
 
@@ -1,10 +1,11 @@
1
+ import { setImmediate } from 'node:timers/promises';
1
2
  import { afterEach, describe, expect, it, rs } from '@rstest/core';
3
+ import { Component, type ReactNode } from 'react';
2
4
  import { renderToMarkdownString } from 'react-render-to-markdown';
5
+ import { useStorageValue } from '../../logic/useStorageValue';
3
6
  import { Tab, Tabs } from './index';
4
7
 
5
- rs.mock('@rspress/core/theme', () => ({
6
- useStorageValue: () => ['0', () => {}],
7
- }));
8
+ rs.mock('@rspress/core/theme', () => ({ useStorageValue }));
8
9
 
9
10
  const originalSsgMd = import.meta.env.SSG_MD;
10
11
 
@@ -24,9 +25,27 @@ afterEach(() => {
24
25
  describe('Tabs', () => {
25
26
  it('renders every tab as markdown when SSG_MD is enabled', async () => {
26
27
  setSsgMd(true);
28
+ expect(typeof window).toBe('undefined');
27
29
 
28
- expect(
29
- await renderToMarkdownString(
30
+ const errors: Error[] = [];
31
+ class ErrorBoundary extends Component<{ children: ReactNode }> {
32
+ state = { hasError: false };
33
+
34
+ static getDerivedStateFromError() {
35
+ return { hasError: true };
36
+ }
37
+
38
+ componentDidCatch(error: Error) {
39
+ errors.push(error);
40
+ }
41
+
42
+ render() {
43
+ return this.state.hasError ? null : this.props.children;
44
+ }
45
+ }
46
+
47
+ const markdown = await renderToMarkdownString(
48
+ <ErrorBoundary>
30
49
  <Tabs>
31
50
  <Tab label="npm" value="npm">
32
51
  npm install
@@ -34,9 +53,13 @@ describe('Tabs', () => {
34
53
  <Tab label="pnpm" value="pnpm">
35
54
  pnpm install
36
55
  </Tab>
37
- </Tabs>,
38
- ),
39
- ).toMatchInlineSnapshot(`
56
+ </Tabs>
57
+ </ErrorBoundary>,
58
+ );
59
+ // Storage subscriptions run after the Markdown renderer resolves its commit.
60
+ await setImmediate();
61
+ expect(errors).toEqual([]);
62
+ expect(markdown).toMatchInlineSnapshot(`
40
63
  "
41
64
  **npm**
42
65
 
@@ -1,5 +1,5 @@
1
1
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
2
- import { useSearchParams } from "@rspress/core/runtime";
2
+ import { useLocation, useSearchParams } from "@rspress/core/runtime";
3
3
  import clsx from "clsx";
4
4
  import { Children, forwardRef, isValidElement, useEffect, useMemo } from "react";
5
5
  import "./index.css";
@@ -17,19 +17,22 @@ function getTabValuesFromChildren(children) {
17
17
  }
18
18
  function usePageTabs(id, children) {
19
19
  const [searchParams, setSearchParams] = useSearchParams();
20
+ const { search } = useLocation();
20
21
  const tabValues = useMemo(()=>getTabValuesFromChildren(children), [
21
22
  children
22
23
  ]);
23
24
  function navigateToTab(index) {
24
- if (0 === index) searchParams.delete(id);
25
- else searchParams.set(id, String(index));
26
- setSearchParams(searchParams);
25
+ const nextSearchParams = new URLSearchParams(searchParams);
26
+ if (0 === index) nextSearchParams.delete(id);
27
+ else nextSearchParams.set(id, String(index));
28
+ setSearchParams(nextSearchParams);
27
29
  }
28
30
  useEffect(()=>{
29
- const currIndex = Number(searchParams.get(id) ?? '0');
31
+ const currIndex = Number(new URLSearchParams(search).get(id) ?? '0');
30
32
  if (!Number.isNaN(currIndex)) document.body.dataset.pageTabsActiveIndex = currIndex.toString();
31
33
  }, [
32
- searchParams
34
+ id,
35
+ search
33
36
  ]);
34
37
  const injectScript = `(function () {
35
38
  var searchParams = new URLSearchParams(window.location.search);
@@ -44,12 +47,10 @@ function usePageTabs(id, children) {
44
47
  injectScript
45
48
  };
46
49
  }
47
- let renderCountForTocUpdate = 0;
48
50
  const PageTabs = /*#__PURE__*/ forwardRef((props, ref)=>{
49
51
  const { children: rawChildren, tabPosition = 'left', className, id = 'page' } = props;
50
52
  const children = Children.toArray(rawChildren).filter((child)=>!('string' == typeof child && '' === child.trim()) && /*#__PURE__*/ isValidElement(child));
51
53
  const { tabValues, navigateToTab, injectScript } = usePageTabs(id, children);
52
- renderCountForTocUpdate++;
53
54
  return /*#__PURE__*/ jsxs(Fragment, {
54
55
  children: [
55
56
  /*#__PURE__*/ jsx("script", {
@@ -85,12 +86,7 @@ const PageTabs = /*#__PURE__*/ forwardRef((props, ref)=>{
85
86
  }, 'string' == typeof label ? label : index))
86
87
  })
87
88
  ]
88
- }),
89
- renderCountForTocUpdate % 2 === 0 ? /*#__PURE__*/ jsx("h2", {
90
- style: {
91
- display: 'none'
92
- }
93
- }) : null
89
+ })
94
90
  ]
95
91
  });
96
92
  });
@@ -1,4 +1,4 @@
1
- import { jsx, jsxs } from "react/jsx-runtime";
1
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
2
2
  import { useI18n } from "@rspress/core/runtime";
3
3
  import { IconArrowDown, IconCopy, IconSuccess, SvgWrapper, copyToClipboard, renderInlineMarkdown } from "@rspress/core/theme";
4
4
  import clsx from "clsx";
@@ -251,6 +251,34 @@ function CopyablePrompt({ className, defaultCollapsed = true, description, eyebr
251
251
  });
252
252
  }
253
253
  function Prompt({ custom = false, ...props }) {
254
+ if (import.meta.env.SSG_MD) {
255
+ const { children, description, eyebrow = 'For your Agent', prompt, title = 'Agent Prompt' } = props;
256
+ if (custom) return /*#__PURE__*/ jsxs(Fragment, {
257
+ children: [
258
+ /*#__PURE__*/ jsx("p", {
259
+ children: /*#__PURE__*/ jsx("strong", {
260
+ children: eyebrow
261
+ })
262
+ }),
263
+ children
264
+ ]
265
+ });
266
+ return /*#__PURE__*/ jsxs(Fragment, {
267
+ children: [
268
+ /*#__PURE__*/ jsx("p", {
269
+ children: /*#__PURE__*/ jsx("strong", {
270
+ children: title
271
+ })
272
+ }),
273
+ description ? /*#__PURE__*/ jsx("p", {
274
+ children: description
275
+ }) : null,
276
+ prompt ? /*#__PURE__*/ jsx("pre", {
277
+ children: `<prompt>\n${prompt}\n</prompt>`
278
+ }) : null
279
+ ]
280
+ });
281
+ }
254
282
  return custom ? /*#__PURE__*/ jsx(CustomPrompt, {
255
283
  ...props
256
284
  }) : /*#__PURE__*/ jsx(CopyablePrompt, {
@@ -64,17 +64,23 @@ const useWatchToc = ()=>{
64
64
  if (target && !observer) {
65
65
  observer = new MutationObserver((mutationList)=>{
66
66
  let needUpdate = false;
67
- check: for (const mutation of mutationList)for (const nodes of [
68
- mutation.addedNodes,
69
- mutation.removedNodes
70
- ])for (const node of nodes){
71
- if (TOC_HEADING_TAGS.has(node.tagName) || node.parentElement?.closest('h2,h3,h4')) {
67
+ check: for (const mutation of mutationList){
68
+ if ('attributes' === mutation.type) {
72
69
  needUpdate = true;
73
- break check;
70
+ break;
74
71
  }
75
- for (const child of node.childNodes)if (TOC_HEADING_TAGS.has(child.tagName)) {
76
- needUpdate = true;
77
- break check;
72
+ for (const nodes of [
73
+ mutation.addedNodes,
74
+ mutation.removedNodes
75
+ ])for (const node of nodes){
76
+ if (TOC_HEADING_TAGS.has(node.tagName) || node.parentElement?.closest('h2,h3,h4')) {
77
+ needUpdate = true;
78
+ break check;
79
+ }
80
+ for (const child of node.childNodes)if (TOC_HEADING_TAGS.has(child.tagName)) {
81
+ needUpdate = true;
82
+ break check;
83
+ }
78
84
  }
79
85
  }
80
86
  needUpdate && updateHeaders(target, pathname);
@@ -83,6 +89,12 @@ const useWatchToc = ()=>{
83
89
  childList: true,
84
90
  subtree: true
85
91
  });
92
+ observer.observe(document.body, {
93
+ attributes: true,
94
+ attributeFilter: [
95
+ 'data-page-tabs-active-index'
96
+ ]
97
+ });
86
98
  }
87
99
  return ()=>{
88
100
  observer?.disconnect();
@@ -19,6 +19,7 @@ const setStorageItem = (key, value)=>{
19
19
  };
20
20
  const useStorageValue = (key, defaultValue)=>{
21
21
  const subscribe = useCallback((onStoreChange)=>{
22
+ if ("u" < typeof window) return ()=>{};
22
23
  const handleStorage = (event)=>{
23
24
  if (event.key === key || null === event.key) onStoreChange();
24
25
  };
package/dist/y~0.js CHANGED
@@ -1,5 +1,5 @@
1
1
  var package_namespaceObject = {
2
- rE: "2.1.2"
2
+ rE: "2.1.3"
3
3
  };
4
4
  function pMap(iterable, mapper, options) {
5
5
  return mapConcurrently(iterable, mapper, options, false);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rspress/core",
3
- "version": "2.1.2",
3
+ "version": "2.1.3",
4
4
  "description": "The Rspress Documentation Framework",
5
5
  "bugs": "https://github.com/web-infra-dev/rspress/issues",
6
6
  "repository": {
@@ -62,7 +62,7 @@
62
62
  "@mdx-js/react": "^3.1.1",
63
63
  "@rsbuild/core": "^2.2.14",
64
64
  "@rsbuild/plugin-react": "~2.1.1",
65
- "@rspress/shared": "2.1.2",
65
+ "@rspress/shared": "2.1.3",
66
66
  "@shikijs/rehype": "^4.2.0",
67
67
  "@shikijs/transformers": "^4.2.0",
68
68
  "@types/mdast": "^4.0.4",