@rspress/plugin-preview 1.1.1 → 1.2.0
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.
- package/dist/index.d.ts +8 -1
- package/dist/index.js +15 -0
- package/dist/index.js.map +1 -1
- package/dist/utils.d.ts +16 -0
- package/dist/utils.js +57 -0
- package/dist/utils.js.map +1 -0
- package/dist/virtual-demo.js +3 -3
- package/package.json +4 -2
- package/static/global-components/Device.tsx +6 -10
package/dist/index.d.ts
CHANGED
@@ -1,5 +1,12 @@
|
|
1
1
|
import { RouteMeta, RspressPlugin } from '@rspress/shared';
|
2
2
|
|
3
|
+
/**
|
4
|
+
* remove .html extension and validate
|
5
|
+
* @param routePath id from pathname
|
6
|
+
* @returns normalized id
|
7
|
+
*/
|
8
|
+
declare const normalizeId: (routePath: string) => string;
|
9
|
+
|
3
10
|
type Options = {
|
4
11
|
/**
|
5
12
|
* preview in mobile mode or not
|
@@ -33,4 +40,4 @@ declare const demoMeta: Record<string, {
|
|
33
40
|
*/
|
34
41
|
declare function pluginPreview(options?: Options): RspressPlugin;
|
35
42
|
|
36
|
-
export { Options, demoMeta, demoRoutes, pluginPreview, routeMeta };
|
43
|
+
export { Options, demoMeta, demoRoutes, normalizeId, pluginPreview, routeMeta };
|
package/dist/index.js
CHANGED
@@ -269,6 +269,7 @@ var src_exports = {};
|
|
269
269
|
__export(src_exports, {
|
270
270
|
demoMeta: () => demoMeta,
|
271
271
|
demoRoutes: () => demoRoutes,
|
272
|
+
normalizeId: () => normalizeId,
|
272
273
|
pluginPreview: () => pluginPreview,
|
273
274
|
routeMeta: () => routeMeta
|
274
275
|
});
|
@@ -276,6 +277,7 @@ module.exports = __toCommonJS(src_exports);
|
|
276
277
|
var import_path3 = require("path");
|
277
278
|
var import_rspack_plugin_virtual_module = require("rspack-plugin-virtual-module");
|
278
279
|
var import_shared2 = require("@rspress/shared");
|
280
|
+
var import_lodash = require("lodash");
|
279
281
|
|
280
282
|
// src/codeToDemo.ts
|
281
283
|
var import_path2 = require("path");
|
@@ -294,6 +296,10 @@ var toValidVarName = (str) => {
|
|
294
296
|
var generateId = (pageName, index) => {
|
295
297
|
return `_${toValidVarName(pageName)}_${index}`;
|
296
298
|
};
|
299
|
+
var normalizeId = (routePath) => {
|
300
|
+
const result = routePath.replace(/\.(.*)?$/, "");
|
301
|
+
return toValidVarName(result);
|
302
|
+
};
|
297
303
|
var injectDemoBlockImport = (str, path2) => {
|
298
304
|
return `
|
299
305
|
import DemoBlock from '${path2}';
|
@@ -675,6 +681,14 @@ import Demo from ${JSON.stringify(demoComponentPath)}
|
|
675
681
|
`${isMobile ? "mobile" : "web"}.css`
|
676
682
|
),
|
677
683
|
addSSGRoutes() {
|
684
|
+
if (iframePosition === "fixed") {
|
685
|
+
const normalizeRoutes = demoRoutes.map(({ path: item }) => {
|
686
|
+
const fragments = item.split("/").filter(Boolean);
|
687
|
+
const demoId = fragments.pop()?.replace(/_(\d+)$/, "");
|
688
|
+
return { path: `/${fragments.join("/")}/${demoId}` };
|
689
|
+
});
|
690
|
+
return (0, import_lodash.uniqBy)(normalizeRoutes, "path");
|
691
|
+
}
|
678
692
|
return demoRoutes;
|
679
693
|
}
|
680
694
|
};
|
@@ -683,6 +697,7 @@ import Demo from ${JSON.stringify(demoComponentPath)}
|
|
683
697
|
0 && (module.exports = {
|
684
698
|
demoMeta,
|
685
699
|
demoRoutes,
|
700
|
+
normalizeId,
|
686
701
|
pluginPreview,
|
687
702
|
routeMeta
|
688
703
|
});
|
package/dist/index.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0MA,SAAS,WAAW,OAAO;AAEzB,QAAM,SAAS,CAAC;AAChB,MAAI,QAAQ;AAEZ,SAAO,EAAE,QAAQ,MAAM,QAAQ;AAC7B,WAAO,KAAK,IAAI,QAAQ,MAAM,KAAK,CAAC;AAAA,EACtC;AAEA,SAAO,YAAY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AAO;AAClB,gBAAM,OACH,KAAK,KAAK,EACV,cAAc,KAAK,EACnB,KAAK,cAAc,EACnB,IAAI,EACJ,KAAK,KAAK,EACV,MAAM,SAAS,EACf,OAAO,YAAY,EACnB,cAAc,MAAM,EACpB,IAAI,iBAAiB,EACrB,WAAO,mBAAK,WAAW,wBAAwB,CAAC,EAChD,IAAI;AAEP,gBAAM,QAAQ,WAAW,QAAQ,KAAK,EAAE,QAAQ,MAAM;AAAA,QACxD;AAAA,MACF;AAAA,IACF;AAAA,IACA,UAAU;AAAA,MACR,eAAe;AAAA,QACb;AAAA,UACE;AAAA,UACA,EAAE,UAAU,cAAc,gBAAgB,kBAAkB;AAAA,QAC9D;AAAA,MACF;AAAA,MACA,kBAAkB;AAAA,YAChB,mBAAK,YAAY,qBAAqB,eAAe;AAAA,MACvD;AAAA,IACF;AAAA,IACA;AAAA,IACA,kBAAc;AAAA,MACZ;AAAA,MACA;AAAA,MACA,GAAG,WAAW,WAAW,KAAK;AAAA,IAChC;AAAA,IACA,eAAe;AACb,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":["index","is","visit","path","routeMeta","externalDemoIndex","fs","pageName"],"sources":["../../../node_modules/.pnpm/unist-util-is@5.2.1/node_modules/unist-util-is/lib/index.js","../../../node_modules/.pnpm/unist-util-is@5.2.1/node_modules/unist-util-is/index.js","../../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/lib/color.js","../../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/lib/index.js","../../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/index.js","../../../node_modules/.pnpm/unist-util-visit@4.1.1/node_modules/unist-util-visit/index.js","../src/index.ts","../src/codeToDemo.ts","../src/utils.ts","../src/constant.ts"],"sourcesContent":["/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n */\n\n/**\n * @typedef {Record<string, unknown>} Props\n * @typedef {null | undefined | string | Props | TestFunctionAnything | Array<string | Props | TestFunctionAnything>} Test\n * Check for an arbitrary node, unaware of TypeScript inferral.\n *\n * @callback TestFunctionAnything\n * Check if a node passes a test, unaware of TypeScript inferral.\n * @param {unknown} this\n * The given context.\n * @param {Node} node\n * A node.\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {boolean | void}\n * Whether this node passes the test.\n */\n\n/**\n * @template {Node} Kind\n * Node type.\n * @typedef {Kind['type'] | Partial<Kind> | TestFunctionPredicate<Kind> | Array<Kind['type'] | Partial<Kind> | TestFunctionPredicate<Kind>>} PredicateTest\n * Check for a node that can be inferred by TypeScript.\n */\n\n/**\n * Check if a node passes a certain test.\n *\n * @template {Node} Kind\n * Node type.\n * @callback TestFunctionPredicate\n * Complex test function for a node that can be inferred by TypeScript.\n * @param {Node} node\n * A node.\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {node is Kind}\n * Whether this node passes the test.\n */\n\n/**\n * @callback AssertAnything\n * Check that an arbitrary value is a node, unaware of TypeScript inferral.\n * @param {unknown} [node]\n * Anything (typically a node).\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {boolean}\n * Whether this is a node and passes a test.\n */\n\n/**\n * Check if a node is a node and passes a certain node test.\n *\n * @template {Node} Kind\n * Node type.\n * @callback AssertPredicate\n * Check that an arbitrary value is a specific node, aware of TypeScript.\n * @param {unknown} [node]\n * Anything (typically a node).\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {node is Kind}\n * Whether this is a node and passes a test.\n */\n\n/**\n * Check if `node` is a `Node` and whether it passes the given test.\n *\n * @param node\n * Thing to check, typically `Node`.\n * @param test\n * A check for a specific node.\n * @param index\n * The node’s position in its parent.\n * @param parent\n * The node’s parent.\n * @returns\n * Whether `node` is a node and passes a test.\n */\nexport const is =\n /**\n * @type {(\n * (() => false) &\n * (<Kind extends Node = Node>(node: unknown, test: PredicateTest<Kind>, index: number, parent: Parent, context?: unknown) => node is Kind) &\n * (<Kind extends Node = Node>(node: unknown, test: PredicateTest<Kind>, index?: null | undefined, parent?: null | undefined, context?: unknown) => node is Kind) &\n * ((node: unknown, test: Test, index: number, parent: Parent, context?: unknown) => boolean) &\n * ((node: unknown, test?: Test, index?: null | undefined, parent?: null | undefined, context?: unknown) => boolean)\n * )}\n */\n (\n /**\n * @param {unknown} [node]\n * @param {Test} [test]\n * @param {number | null | undefined} [index]\n * @param {Parent | null | undefined} [parent]\n * @param {unknown} [context]\n * @returns {boolean}\n */\n // eslint-disable-next-line max-params\n function is(node, test, index, parent, context) {\n const check = convert(test)\n\n if (\n index !== undefined &&\n index !== null &&\n (typeof index !== 'number' ||\n index < 0 ||\n index === Number.POSITIVE_INFINITY)\n ) {\n throw new Error('Expected positive finite index')\n }\n\n if (\n parent !== undefined &&\n parent !== null &&\n (!is(parent) || !parent.children)\n ) {\n throw new Error('Expected parent node')\n }\n\n if (\n (parent === undefined || parent === null) !==\n (index === undefined || index === null)\n ) {\n throw new Error('Expected both parent and index')\n }\n\n // @ts-expect-error Looks like a node.\n return node && node.type && typeof node.type === 'string'\n ? Boolean(check.call(context, node, index, parent))\n : false\n }\n )\n\n/**\n * Generate an assertion from a test.\n *\n * Useful if you’re going to test many nodes, for example when creating a\n * utility where something else passes a compatible test.\n *\n * The created function is a bit faster because it expects valid input only:\n * a `node`, `index`, and `parent`.\n *\n * @param test\n * * when nullish, checks if `node` is a `Node`.\n * * when `string`, works like passing `(node) => node.type === test`.\n * * when `function` checks if function passed the node is true.\n * * when `object`, checks that all keys in test are in node, and that they have (strictly) equal values.\n * * when `array`, checks if any one of the subtests pass.\n * @returns\n * An assertion.\n */\nexport const convert =\n /**\n * @type {(\n * (<Kind extends Node>(test: PredicateTest<Kind>) => AssertPredicate<Kind>) &\n * ((test?: Test) => AssertAnything)\n * )}\n */\n (\n /**\n * @param {Test} [test]\n * @returns {AssertAnything}\n */\n function (test) {\n if (test === undefined || test === null) {\n return ok\n }\n\n if (typeof test === 'string') {\n return typeFactory(test)\n }\n\n if (typeof test === 'object') {\n return Array.isArray(test) ? anyFactory(test) : propsFactory(test)\n }\n\n if (typeof test === 'function') {\n return castFactory(test)\n }\n\n throw new Error('Expected function, string, or object as test')\n }\n )\n\n/**\n * @param {Array<string | Props | TestFunctionAnything>} tests\n * @returns {AssertAnything}\n */\nfunction anyFactory(tests) {\n /** @type {Array<AssertAnything>} */\n const checks = []\n let index = -1\n\n while (++index < tests.length) {\n checks[index] = convert(tests[index])\n }\n\n return castFactory(any)\n\n /**\n * @this {unknown}\n * @param {Array<unknown>} parameters\n * @returns {boolean}\n */\n function any(...parameters) {\n let index = -1\n\n while (++index < checks.length) {\n if (checks[index].call(this, ...parameters)) return true\n }\n\n return false\n }\n}\n\n/**\n * Turn an object into a test for a node with a certain fields.\n *\n * @param {Props} check\n * @returns {AssertAnything}\n */\nfunction propsFactory(check) {\n return castFactory(all)\n\n /**\n * @param {Node} node\n * @returns {boolean}\n */\n function all(node) {\n /** @type {string} */\n let key\n\n for (key in check) {\n // @ts-expect-error: hush, it sure works as an index.\n if (node[key] !== check[key]) return false\n }\n\n return true\n }\n}\n\n/**\n * Turn a string into a test for a node with a certain type.\n *\n * @param {string} check\n * @returns {AssertAnything}\n */\nfunction typeFactory(check) {\n return castFactory(type)\n\n /**\n * @param {Node} node\n */\n function type(node) {\n return node && node.type === check\n }\n}\n\n/**\n * Turn a custom test into a test for a node that passes that test.\n *\n * @param {TestFunctionAnything} check\n * @returns {AssertAnything}\n */\nfunction castFactory(check) {\n return assertion\n\n /**\n * @this {unknown}\n * @param {unknown} node\n * @param {Array<unknown>} parameters\n * @returns {boolean}\n */\n function assertion(node, ...parameters) {\n return Boolean(\n node &&\n typeof node === 'object' &&\n 'type' in node &&\n // @ts-expect-error: fine.\n Boolean(check.call(this, node, ...parameters))\n )\n }\n}\n\nfunction ok() {\n return true\n}\n","/**\n * @typedef {import('./lib/index.js').Test} Test\n * @typedef {import('./lib/index.js').TestFunctionAnything} TestFunctionAnything\n * @typedef {import('./lib/index.js').AssertAnything} AssertAnything\n */\n\n/**\n * @template {import('unist').Node} Kind\n * @typedef {import('./lib/index.js').PredicateTest<Kind>} PredicateTest\n */\n\n/**\n * @template {import('unist').Node} Kind\n * @typedef {import('./lib/index.js').TestFunctionPredicate<Kind>} TestFunctionPredicate\n */\n\n/**\n * @template {import('unist').Node} Kind\n * @typedef {import('./lib/index.js').AssertPredicate<Kind>} AssertPredicate\n */\n\nexport {is, convert} from './lib/index.js'\n","/**\n * @param {string} d\n * @returns {string}\n */\nexport function color(d) {\n return '\\u001B[33m' + d + '\\u001B[39m'\n}\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n * @typedef {import('unist-util-is').Test} Test\n */\n\n/**\n * @typedef {boolean | 'skip'} Action\n * Union of the action types.\n *\n * @typedef {number} Index\n * Move to the sibling at `index` next (after node itself is completely\n * traversed).\n *\n * Useful if mutating the tree, such as removing the node the visitor is\n * currently on, or any of its previous siblings.\n * Results less than 0 or greater than or equal to `children.length` stop\n * traversing the parent.\n *\n * @typedef {[(Action | null | undefined | void)?, (Index | null | undefined)?]} ActionTuple\n * List with one or two values, the first an action, the second an index.\n *\n * @typedef {Action | ActionTuple | Index | null | undefined | void} VisitorResult\n * Any value that can be returned from a visitor.\n */\n\n/**\n * @template {Node} [Visited=Node]\n * Visited node type.\n * @template {Parent} [Ancestor=Parent]\n * Ancestor type.\n * @callback Visitor\n * Handle a node (matching `test`, if given).\n *\n * Visitors are free to transform `node`.\n * They can also transform the parent of node (the last of `ancestors`).\n *\n * Replacing `node` itself, if `SKIP` is not returned, still causes its\n * descendants to be walked (which is a bug).\n *\n * When adding or removing previous siblings of `node` (or next siblings, in\n * case of reverse), the `Visitor` should return a new `Index` to specify the\n * sibling to traverse after `node` is traversed.\n * Adding or removing next siblings of `node` (or previous siblings, in case\n * of reverse) is handled as expected without needing to return a new `Index`.\n *\n * Removing the children property of an ancestor still results in them being\n * traversed.\n * @param {Visited} node\n * Found node.\n * @param {Array<Ancestor>} ancestors\n * Ancestors of `node`.\n * @returns {VisitorResult}\n * What to do next.\n *\n * An `Index` is treated as a tuple of `[CONTINUE, Index]`.\n * An `Action` is treated as a tuple of `[Action]`.\n *\n * Passing a tuple back only makes sense if the `Action` is `SKIP`.\n * When the `Action` is `EXIT`, that action can be returned.\n * When the `Action` is `CONTINUE`, `Index` can be returned.\n */\n\n/**\n * @template {Node} [Tree=Node]\n * Tree type.\n * @template {Test} [Check=string]\n * Test type.\n * @typedef {Visitor<import('./complex-types.js').Matches<import('./complex-types.js').InclusiveDescendant<Tree>, Check>, Extract<import('./complex-types.js').InclusiveDescendant<Tree>, Parent>>} BuildVisitor\n * Build a typed `Visitor` function from a tree and a test.\n *\n * It will infer which values are passed as `node` and which as `parents`.\n */\n\nimport {convert} from 'unist-util-is'\nimport {color} from './color.js'\n\n/**\n * Continue traversing as normal.\n */\nexport const CONTINUE = true\n\n/**\n * Stop traversing immediately.\n */\nexport const EXIT = false\n\n/**\n * Do not traverse this node’s children.\n */\nexport const SKIP = 'skip'\n\n/**\n * Visit nodes, with ancestral information.\n *\n * This algorithm performs *depth-first* *tree traversal* in *preorder*\n * (**NLR**) or if `reverse` is given, in *reverse preorder* (**NRL**).\n *\n * You can choose for which nodes `visitor` is called by passing a `test`.\n * For complex tests, you should test yourself in `visitor`, as it will be\n * faster and will have improved type information.\n *\n * Walking the tree is an intensive task.\n * Make use of the return values of the visitor when possible.\n * Instead of walking a tree multiple times, walk it once, use `unist-util-is`\n * to check if a node matches, and then perform different operations.\n *\n * You can change the tree.\n * See `Visitor` for more info.\n *\n * @param tree\n * Tree to traverse.\n * @param test\n * `unist-util-is`-compatible test\n * @param visitor\n * Handle each node.\n * @param reverse\n * Traverse in reverse preorder (NRL) instead of the default preorder (NLR).\n * @returns\n * Nothing.\n */\nexport const visitParents =\n /**\n * @type {(\n * (<Tree extends Node, Check extends Test>(tree: Tree, test: Check, visitor: BuildVisitor<Tree, Check>, reverse?: boolean | null | undefined) => void) &\n * (<Tree extends Node>(tree: Tree, visitor: BuildVisitor<Tree>, reverse?: boolean | null | undefined) => void)\n * )}\n */\n (\n /**\n * @param {Node} tree\n * @param {Test} test\n * @param {Visitor<Node>} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {void}\n */\n function (tree, test, visitor, reverse) {\n if (typeof test === 'function' && typeof visitor !== 'function') {\n reverse = visitor\n // @ts-expect-error no visitor given, so `visitor` is test.\n visitor = test\n test = null\n }\n\n const is = convert(test)\n const step = reverse ? -1 : 1\n\n factory(tree, undefined, [])()\n\n /**\n * @param {Node} node\n * @param {number | undefined} index\n * @param {Array<Parent>} parents\n */\n function factory(node, index, parents) {\n /** @type {Record<string, unknown>} */\n // @ts-expect-error: hush\n const value = node && typeof node === 'object' ? node : {}\n\n if (typeof value.type === 'string') {\n const name =\n // `hast`\n typeof value.tagName === 'string'\n ? value.tagName\n : // `xast`\n typeof value.name === 'string'\n ? value.name\n : undefined\n\n Object.defineProperty(visit, 'name', {\n value:\n 'node (' + color(node.type + (name ? '<' + name + '>' : '')) + ')'\n })\n }\n\n return visit\n\n function visit() {\n /** @type {ActionTuple} */\n let result = []\n /** @type {ActionTuple} */\n let subresult\n /** @type {number} */\n let offset\n /** @type {Array<Parent>} */\n let grandparents\n\n if (!test || is(node, index, parents[parents.length - 1] || null)) {\n result = toResult(visitor(node, parents))\n\n if (result[0] === EXIT) {\n return result\n }\n }\n\n // @ts-expect-error looks like a parent.\n if (node.children && result[0] !== SKIP) {\n // @ts-expect-error looks like a parent.\n offset = (reverse ? node.children.length : -1) + step\n // @ts-expect-error looks like a parent.\n grandparents = parents.concat(node)\n\n // @ts-expect-error looks like a parent.\n while (offset > -1 && offset < node.children.length) {\n // @ts-expect-error looks like a parent.\n subresult = factory(node.children[offset], offset, grandparents)()\n\n if (subresult[0] === EXIT) {\n return subresult\n }\n\n offset =\n typeof subresult[1] === 'number' ? subresult[1] : offset + step\n }\n }\n\n return result\n }\n }\n }\n )\n\n/**\n * Turn a return value into a clean result.\n *\n * @param {VisitorResult} value\n * Valid return values from visitors.\n * @returns {ActionTuple}\n * Clean result.\n */\nfunction toResult(value) {\n if (Array.isArray(value)) {\n return value\n }\n\n if (typeof value === 'number') {\n return [CONTINUE, value]\n }\n\n return [value]\n}\n","// Note: types exported from `index.d.ts`\nexport {CONTINUE, EXIT, SKIP, visitParents} from './lib/index.js'\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n * @typedef {import('unist-util-is').Test} Test\n * @typedef {import('unist-util-visit-parents').VisitorResult} VisitorResult\n * @typedef {import('./complex-types.js').Visitor} Visitor\n */\n\nimport {visitParents} from 'unist-util-visit-parents'\n\n/**\n * Visit children of tree which pass test.\n *\n * @param tree\n * Tree to walk\n * @param [test]\n * `unist-util-is`-compatible test\n * @param visitor\n * Function called for nodes that pass `test`.\n * @param reverse\n * Traverse in reverse preorder (NRL) instead of preorder (NLR) (default).\n */\nexport const visit =\n /**\n * @type {(\n * (<Tree extends Node, Check extends Test>(tree: Tree, test: Check, visitor: import('./complex-types.js').BuildVisitor<Tree, Check>, reverse?: boolean) => void) &\n * (<Tree extends Node>(tree: Tree, visitor: import('./complex-types.js').BuildVisitor<Tree>, reverse?: boolean) => void)\n * )}\n */\n (\n /**\n * @param {Node} tree\n * @param {Test} test\n * @param {import('./complex-types.js').Visitor} visitor\n * @param {boolean} [reverse]\n */\n function (tree, test, visitor, reverse) {\n if (typeof test === 'function' && typeof visitor !== 'function') {\n reverse = visitor\n visitor = test\n test = null\n }\n\n visitParents(tree, test, overload, reverse)\n\n /**\n * @param {Node} node\n * @param {Array<Parent>} parents\n */\n function overload(node, parents) {\n const parent = parents[parents.length - 1]\n return visitor(\n node,\n parent ? parent.children.indexOf(node) : null,\n parent\n )\n }\n }\n )\n\nexport {CONTINUE, EXIT, SKIP} from 'unist-util-visit-parents'\n","import { join, parse, extname } from 'path';\nimport { RspackVirtualModulePlugin } from 'rspack-plugin-virtual-module';\nimport {\n type RspressPlugin,\n type RouteMeta,\n RSPRESS_TEMP_DIR,\n normalizePosixPath,\n} from '@rspress/shared';\nimport { remarkCodeToDemo } from './codeToDemo';\nimport { generateId, injectDemoBlockImport } from './utils';\nimport {\n demoBlockComponentPath,\n demoComponentPath,\n staticPath,\n} from './constant';\n\nexport type Options = {\n /**\n * preview in mobile mode or not\n * when isMobile is true, 1. aside will hide. 2. default preview component by iframe\n * @default false\n */\n isMobile?: boolean;\n /**\n * position of the iframe\n * @default 'follow'\n */\n iframePosition?: 'fixed' | 'follow';\n /**\n * whether the demo can open in codesandbox\n * @default false\n * @experimental\n */\n enableCodesandbox?: boolean;\n};\n\ninterface Heading {\n type: string;\n depth?: number;\n children?: ChildNode[];\n}\n\ninterface ChildNode {\n type: 'link' | 'text' | 'inlineCode';\n value: string;\n children?: ChildNode[];\n}\n\n// eslint-disable-next-line import/no-mutable-exports\nexport let routeMeta: RouteMeta[];\nexport const demoRoutes: { path: string }[] = [];\nexport const demoMeta: Record<\n string,\n { id: string; virtualModulePath: string; title: string }[]\n> = {};\n\n/**\n * The plugin is used to preview component.\n */\nexport function pluginPreview(options?: Options): RspressPlugin {\n const isMobile = options?.isMobile ?? false;\n const iframePosition = options?.iframePosition ?? 'follow';\n const enableCodesandbox = options?.enableCodesandbox ?? false;\n const demoRuntimeModule = new RspackVirtualModulePlugin({});\n const globalUIComponents =\n iframePosition === 'fixed'\n ? [join(staticPath, 'global-components', 'Device.tsx')]\n : [];\n const getRouteMeta = () => routeMeta;\n return {\n name: '@rspress/plugin-preview',\n config(config) {\n config.markdown = config.markdown || {};\n config.markdown.mdxRs = false;\n return config;\n },\n addPages(_config, _isProd) {\n return [\n {\n routePath: '/~demo/:id',\n content: `---\npageType: \"blank\"\n---\n\nimport Demo from ${JSON.stringify(demoComponentPath)}\n\n<Demo iframePosition=\"${iframePosition}\"/>\n `,\n },\n ];\n },\n async routeGenerated(routes: RouteMeta[]) {\n // init routeMeta\n routeMeta = routes;\n\n const files = routes.map(route => route.absolutePath);\n // Write the demo code ahead of time\n // Fix: rspack build error because demo file is not exist, probably the demo file was written in rspack build process?\n await Promise.all(\n files.map(async (filepath, _index) => {\n const isMdxFile = /\\.mdx?$/.test(filepath);\n if (!isMdxFile) {\n return;\n }\n const { createProcessor } = await import('@mdx-js/mdx');\n const { visit } = await import('unist-util-visit');\n const { default: fs } = await import('@modern-js/utils/fs-extra');\n const { default: remarkGFM } = await import('remark-gfm');\n let title = parse(filepath).name;\n try {\n const processor = createProcessor({\n format: extname(filepath).slice(1) as 'mdx' | 'md',\n remarkPlugins: [remarkGFM],\n });\n const source = await fs.readFile(filepath, 'utf-8');\n const ast = processor.parse(source);\n let index = 1;\n const { pageName } = routeMeta.find(\n meta =>\n normalizePosixPath(meta.absolutePath) ===\n normalizePosixPath(filepath),\n )!;\n\n const registerDemo = (\n demoId: string,\n demoPath: string,\n isMobileMode: boolean,\n ) => {\n if (isMobileMode) {\n // only add demoMeta in mobile mode\n demoMeta[filepath] = demoMeta[filepath] ?? [];\n const isExist = demoMeta[filepath].find(\n item => item.id === demoId,\n );\n if (!isExist) {\n demoMeta[filepath].push({\n id: demoId,\n title,\n virtualModulePath: demoPath,\n });\n }\n }\n };\n visit(ast, 'heading', (node: Heading) => {\n if (node.depth === 1) {\n if (node.children) {\n title = node.children[0].value;\n }\n }\n });\n\n visit(ast, 'mdxJsxFlowElement', (node: any) => {\n if (node.name === 'code') {\n const src = node.attributes.find(\n (attr: { name: string; value: string }) =>\n attr.name === 'src',\n )?.value;\n const isMobileMode =\n node.attributes.find(\n (attr: { name: string; value: boolean }) =>\n attr.name === 'isMobile',\n )?.value ?? isMobile;\n if (!src) {\n return;\n }\n const id = generateId(pageName, index++);\n registerDemo(id, src, isMobileMode);\n }\n });\n\n visit(ast, 'code', (node: any) => {\n if (node.lang === 'jsx' || node.lang === 'tsx') {\n const { value } = node;\n const isPure = node?.meta?.includes('pure');\n\n // do not anything for pure mode\n if (isPure) {\n return;\n }\n\n // every code block can change their preview mode by meta\n const isMobileMode =\n node?.meta?.includes('mobile') ||\n (!node?.meta?.includes('web') && isMobile);\n\n const { pageName } = routeMeta.find(\n meta =>\n normalizePosixPath(meta.absolutePath) ===\n normalizePosixPath(filepath),\n )!;\n const id = generateId(pageName, index++);\n\n const demoDir = join(\n process.cwd(),\n 'node_modules',\n RSPRESS_TEMP_DIR,\n `virtual-demo`,\n );\n\n const virtualModulePath = join(demoDir, `${id}.tsx`);\n registerDemo(id, virtualModulePath, isMobileMode);\n\n fs.ensureDirSync(join(demoDir));\n fs.writeFileSync(\n virtualModulePath,\n injectDemoBlockImport(value, demoBlockComponentPath),\n );\n }\n });\n } catch (e) {\n console.error(e);\n throw e;\n }\n }),\n );\n /**\n * expect the meta of each demo file is like this:\n * {\n * id,\n * component,\n * }\n */\n const virtualMeta = `\n ${files\n .map((filepath, index) => {\n return `import Route${index} from '${filepath}?meta';`;\n })\n .join('\\n')}\n export const demos = [${files\n .map((_, index) => `Route${index}`)\n .flat()\n .join(',')}];\n `;\n demoRuntimeModule.writeModule('virtual-meta', virtualMeta);\n },\n builderConfig: {\n tools: {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment, @typescript-eslint/prefer-ts-expect-error\n // @ts-ignore\n rspack: {\n plugins: [demoRuntimeModule],\n },\n bundlerChain(chain) {\n chain.module\n .rule('Raw')\n .resourceQuery(/raw/)\n .type('asset/source')\n .end()\n .rule('MDX')\n .oneOf('MDXMeta')\n .before('MDXCompile')\n .resourceQuery(/meta/)\n .use('mdx-meta-loader')\n .loader(join(__dirname, '../mdx-meta-loader.cjs'))\n .end();\n\n chain.resolve.extensions.prepend('.md').prepend('.mdx');\n },\n },\n },\n markdown: {\n remarkPlugins: [\n [\n remarkCodeToDemo,\n { isMobile, getRouteMeta, iframePosition, enableCodesandbox },\n ],\n ],\n globalComponents: [\n join(staticPath, 'global-components', 'Container.tsx'),\n ],\n },\n globalUIComponents,\n globalStyles: join(\n staticPath,\n 'global-styles',\n `${isMobile ? 'mobile' : 'web'}.css`,\n ),\n addSSGRoutes() {\n return demoRoutes;\n },\n };\n}\n","import { join, resolve } from 'path';\nimport { visit } from 'unist-util-visit';\nimport fs from '@modern-js/utils/fs-extra';\nimport {\n RSPRESS_TEMP_DIR,\n normalizePosixPath,\n type RouteMeta,\n} from '@rspress/shared';\nimport type { Plugin } from 'unified';\nimport type { Root } from 'mdast';\nimport type { MdxjsEsm } from 'mdast-util-mdxjs-esm';\nimport { injectDemoBlockImport, generateId } from './utils';\nimport { demoBlockComponentPath } from './constant';\nimport { demoRoutes } from '.';\n\n// FIXME: remove it\nconst json = JSON.parse(\n fs.readFileSync(resolve(process.cwd(), './package.json'), 'utf8'),\n);\n\n/**\n * remark plugin to transform code to demo\n */\nexport const remarkCodeToDemo: Plugin<\n [\n {\n isMobile: boolean;\n getRouteMeta: () => RouteMeta[];\n iframePosition: 'fixed' | 'follow';\n enableCodesandbox: boolean;\n },\n ],\n Root\n> = ({ isMobile, getRouteMeta, iframePosition, enableCodesandbox }) => {\n const routeMeta = getRouteMeta();\n\n return (tree, vfile) => {\n const demos: MdxjsEsm[] = [];\n const route = routeMeta.find(\n meta =>\n normalizePosixPath(meta.absolutePath) ===\n normalizePosixPath(vfile.path || vfile.history[0]),\n );\n if (!route) {\n return;\n }\n const { pageName } = route;\n let index = 1;\n let externalDemoIndex = 0;\n\n function constructDemoNode(\n demoId: string,\n demoPath: string,\n currentNode: any,\n isMobileMode: boolean,\n // Only for external demo\n externalDemoIndex?: number,\n ) {\n const demoRoute = `/~demo/${demoId}`;\n if (isMobileMode) {\n // only add demoRoutes in mobile mode\n demoRoutes.push({\n path: demoRoute,\n });\n } else {\n demos.push(getASTNodeImport(`Demo${demoId}`, demoPath));\n }\n\n // get external demo content\n const tempVar = `externalDemoContent${externalDemoIndex}`;\n if (externalDemoIndex !== undefined) {\n demos.push(getASTNodeImport(tempVar, `${demoPath}?raw`));\n }\n\n if (isMobileMode && iframePosition === 'fixed') {\n // Only show the code block\n externalDemoIndex !== undefined &&\n Object.assign(currentNode, getExternalDemoContent(tempVar));\n } else {\n // Use container to show the code and view\n Object.assign(currentNode, {\n type: 'mdxJsxFlowElement',\n name: 'Container',\n attributes: [\n {\n type: 'mdxJsxAttribute',\n name: 'isMobile',\n value: isMobileMode,\n },\n {\n type: 'mdxJsxAttribute',\n name: 'url',\n value: demoRoute,\n },\n {\n type: 'mdxJsxAttribute',\n name: 'content',\n value: currentNode.value,\n },\n {\n type: 'mdxJsxAttribute',\n name: 'packageName',\n value: json.name,\n },\n {\n type: 'mdxJsxAttribute',\n name: 'enableCodesandbox',\n value: enableCodesandbox,\n },\n ],\n children: [\n externalDemoIndex === undefined\n ? {\n ...currentNode,\n hasVisited: true,\n }\n : getExternalDemoContent(tempVar),\n isMobileMode\n ? {\n type: 'mdxJsxFlowElement',\n name: null,\n }\n : {\n type: 'mdxJsxFlowElement',\n name: `Demo${demoId}`,\n },\n ],\n });\n }\n }\n\n // 1. External demo , use <code src=\"xxx\" /> to declare demo\n tree.children.forEach((node: any) => {\n if (node.type === 'mdxJsxFlowElement' && node.name === 'code') {\n const src = node.attributes.find(\n (attr: { name: string; value: string }) => attr.name === 'src',\n )?.value;\n const isMobileMode =\n node.attributes.find(\n (attr: { name: string; value: boolean }) =>\n attr.name === 'isMobile',\n )?.value ?? isMobile;\n if (!src) {\n return;\n }\n const id = generateId(pageName, index++);\n constructDemoNode(id, src, node, isMobileMode, externalDemoIndex++);\n }\n });\n\n // 2. Internal demo, use ```j/tsx to declare demo\n visit(tree, 'code', node => {\n // hasVisited is a custom property\n if ('hasVisited' in node) {\n return;\n }\n\n if (node.lang === 'jsx' || node.lang === 'tsx') {\n const value = injectDemoBlockImport(node.value, demoBlockComponentPath);\n\n const isPure = node?.meta?.includes('pure');\n\n // do nothing for pure mode\n if (isPure) {\n return;\n }\n\n // every code block can change their preview mode by meta\n const isMobileMode =\n node?.meta?.includes('mobile') ||\n (!node?.meta?.includes('web') && isMobile);\n\n const demoDir = join(\n process.cwd(),\n 'node_modules',\n RSPRESS_TEMP_DIR,\n `virtual-demo`,\n );\n const id = generateId(pageName, index++);\n const virtualModulePath = join(demoDir, `${id}.tsx`);\n fs.ensureDirSync(join(demoDir));\n // Only when the content of the file changes, the file will be written\n // Avoid to trigger the hmr indefinitely\n if (fs.existsSync(virtualModulePath)) {\n const content = fs.readFileSync(virtualModulePath, 'utf-8');\n if (content !== value) {\n fs.writeFileSync(virtualModulePath, value);\n }\n }\n constructDemoNode(id, virtualModulePath, node, isMobileMode);\n }\n });\n\n tree.children.unshift(...demos);\n };\n};\n\nconst getASTNodeImport = (name: string, from: string) =>\n ({\n type: 'mdxjsEsm',\n value: `import ${name} from ${JSON.stringify(from)}`,\n data: {\n estree: {\n type: 'Program',\n sourceType: 'module',\n body: [\n {\n type: 'ImportDeclaration',\n specifiers: [\n {\n type: 'ImportDefaultSpecifier',\n local: { type: 'Identifier', name },\n },\n ],\n source: {\n type: 'Literal',\n value: from,\n raw: `${JSON.stringify(from)}`,\n },\n },\n ],\n },\n },\n } as MdxjsEsm);\n\nconst getExternalDemoContent = (tempVar: string) => ({\n type: 'mdxJsxFlowElement',\n name: 'pre',\n children: [\n {\n type: 'mdxJsxFlowElement',\n name: 'code',\n attributes: [\n {\n type: 'mdxJsxAttribute',\n name: 'className',\n value: 'language-tsx',\n },\n {\n type: 'mdxJsxAttribute',\n name: 'children',\n value: {\n type: 'mdxJsxExpressionAttribute',\n value: tempVar,\n data: {\n estree: {\n type: 'Program',\n body: [\n {\n type: 'ExpressionStatement',\n expression: {\n type: 'Identifier',\n name: tempVar,\n },\n },\n ],\n },\n },\n },\n },\n ],\n },\n ],\n});\n","/**\n * Converts a string to a valid variable name. If the string is already a valid variable name, returns the original string.\n * @param str - The string to convert.\n * @returns The converted string.\n */\nexport const toValidVarName = (str: string): string => {\n // Check if the string is a valid variable name\n if (/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(str)) {\n return str; // If it is a valid variable name, return the original string\n } else {\n // If it is not a valid variable name, convert it to a valid variable name\n return str.replace(/[^0-9a-zA-Z_$]/g, '_').replace(/^([0-9])/, '_$1');\n }\n};\n\nexport const generateId = (pageName: string, index: number) => {\n return `_${toValidVarName(pageName)}_${index}`;\n};\n\n/**\n * remove .html extension and validate\n * @param routePath id from pathname\n * @returns normalized id\n */\nexport const normalizeId = (routePath: string) => {\n const result = routePath.replace(/\\.(.*)?$/, '');\n return toValidVarName(result);\n};\n\nexport const injectDemoBlockImport = (str: string, path: string): string => {\n return `\n import DemoBlock from '${path}';\n ${str}\n `;\n};\n","import path from 'path';\n\nexport const staticPath = path.join(__dirname, '..', 'static');\n\nexport const demoComponentPath = path.join(\n __dirname,\n '..',\n 'dist',\n 'virtual-demo.js',\n);\n\nexport const demoBlockComponentPath = path.join(\n staticPath,\n 'global-components',\n 'DemoBlock.tsx',\n);\n"]}
|
1
|
+
{"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0MA,SAAS,WAAW,OAAO;AAEzB,QAAM,SAAS,CAAC;AAChB,MAAI,QAAQ;AAEZ,SAAO,EAAE,QAAQ,MAAM,QAAQ;AAC7B,WAAO,KAAK,IAAI,QAAQ,MAAM,KAAK,CAAC;AAAA,EACtC;AAEA,SAAO,YAAY,GAAG;AAOtB,WAAS,OAAO,YAAY;AAC1B,QAAIA,SAAQ;AAEZ,WAAO,EAAEA,SAAQ,OAAO,QAAQ;AAC9B,UAAI,OAAOA,MAAK,EAAE,KAAK,MAAM,GAAG,UAAU;AAAG,eAAO;AAAA,IACtD;AAEA,WAAO;AAAA,EACT;AACF;AAQA,SAAS,aAAa,OAAO;AAC3B,SAAO,YAAY,GAAG;AAMtB,WAAS,IAAI,MAAM;AAEjB,QAAI;AAEJ,SAAK,OAAO,O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mBAAK,WAAW,wBAAwB,CAAC,EAChD,IAAI;AAEP,gBAAM,QAAQ,WAAW,QAAQ,KAAK,EAAE,QAAQ,MAAM;AAAA,QACxD;AAAA,MACF;AAAA,IACF;AAAA,IACA,UAAU;AAAA,MACR,eAAe;AAAA,QACb;AAAA,UACE;AAAA,UACA,EAAE,UAAU,cAAc,gBAAgB,kBAAkB;AAAA,QAC9D;AAAA,MACF;AAAA,MACA,kBAAkB;AAAA,YAChB,mBAAK,YAAY,qBAAqB,eAAe;AAAA,MACvD;AAAA,IACF;AAAA,IACA;AAAA,IACA,kBAAc;AAAA,MACZ;AAAA,MACA;AAAA,MACA,GAAG,WAAW,WAAW,KAAK;AAAA,IAChC;AAAA,IACA,eAAe;AACb,UAAI,mBAAmB,SAAS;AAC9B,cAAM,kBAAkB,WAAW,IAAI,CAAC,EAAE,MAAM,KAAK,MAAM;AACzD,gBAAM,YAAY,KAAK,MAAM,GAAG,EAAE,OAAO,OAAO;AAChD,gBAAM,SAAS,UAAU,IAAI,GAAG,QAAQ,WAAW,EAAE;AACrD,iBAAO,EAAE,MAAM,IAAI,UAAU,KAAK,GAAG,CAAC,IAAI,MAAM,GAAG;AAAA,QACrD,CAAC;AAED,mBAAO,sBAAO,iBAAiB,MAAM;AAAA,MACvC;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":["index","is","visit","path","routeMeta","externalDemoIndex","fs","pageName"],"sources":["../../../node_modules/.pnpm/unist-util-is@5.2.1/node_modules/unist-util-is/lib/index.js","../../../node_modules/.pnpm/unist-util-is@5.2.1/node_modules/unist-util-is/index.js","../../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/lib/color.js","../../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/lib/index.js","../../../node_modules/.pnpm/unist-util-visit-parents@5.1.3/node_modules/unist-util-visit-parents/index.js","../../../node_modules/.pnpm/unist-util-visit@4.1.1/node_modules/unist-util-visit/index.js","../src/index.ts","../src/codeToDemo.ts","../src/utils.ts","../src/constant.ts"],"sourcesContent":["/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n */\n\n/**\n * @typedef {Record<string, unknown>} Props\n * @typedef {null | undefined | string | Props | TestFunctionAnything | Array<string | Props | TestFunctionAnything>} Test\n * Check for an arbitrary node, unaware of TypeScript inferral.\n *\n * @callback TestFunctionAnything\n * Check if a node passes a test, unaware of TypeScript inferral.\n * @param {unknown} this\n * The given context.\n * @param {Node} node\n * A node.\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {boolean | void}\n * Whether this node passes the test.\n */\n\n/**\n * @template {Node} Kind\n * Node type.\n * @typedef {Kind['type'] | Partial<Kind> | TestFunctionPredicate<Kind> | Array<Kind['type'] | Partial<Kind> | TestFunctionPredicate<Kind>>} PredicateTest\n * Check for a node that can be inferred by TypeScript.\n */\n\n/**\n * Check if a node passes a certain test.\n *\n * @template {Node} Kind\n * Node type.\n * @callback TestFunctionPredicate\n * Complex test function for a node that can be inferred by TypeScript.\n * @param {Node} node\n * A node.\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {node is Kind}\n * Whether this node passes the test.\n */\n\n/**\n * @callback AssertAnything\n * Check that an arbitrary value is a node, unaware of TypeScript inferral.\n * @param {unknown} [node]\n * Anything (typically a node).\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {boolean}\n * Whether this is a node and passes a test.\n */\n\n/**\n * Check if a node is a node and passes a certain node test.\n *\n * @template {Node} Kind\n * Node type.\n * @callback AssertPredicate\n * Check that an arbitrary value is a specific node, aware of TypeScript.\n * @param {unknown} [node]\n * Anything (typically a node).\n * @param {number | null | undefined} [index]\n * The node’s position in its parent.\n * @param {Parent | null | undefined} [parent]\n * The node’s parent.\n * @returns {node is Kind}\n * Whether this is a node and passes a test.\n */\n\n/**\n * Check if `node` is a `Node` and whether it passes the given test.\n *\n * @param node\n * Thing to check, typically `Node`.\n * @param test\n * A check for a specific node.\n * @param index\n * The node’s position in its parent.\n * @param parent\n * The node’s parent.\n * @returns\n * Whether `node` is a node and passes a test.\n */\nexport const is =\n /**\n * @type {(\n * (() => false) &\n * (<Kind extends Node = Node>(node: unknown, test: PredicateTest<Kind>, index: number, parent: Parent, context?: unknown) => node is Kind) &\n * (<Kind extends Node = Node>(node: unknown, test: PredicateTest<Kind>, index?: null | undefined, parent?: null | undefined, context?: unknown) => node is Kind) &\n * ((node: unknown, test: Test, index: number, parent: Parent, context?: unknown) => boolean) &\n * ((node: unknown, test?: Test, index?: null | undefined, parent?: null | undefined, context?: unknown) => boolean)\n * )}\n */\n (\n /**\n * @param {unknown} [node]\n * @param {Test} [test]\n * @param {number | null | undefined} [index]\n * @param {Parent | null | undefined} [parent]\n * @param {unknown} [context]\n * @returns {boolean}\n */\n // eslint-disable-next-line max-params\n function is(node, test, index, parent, context) {\n const check = convert(test)\n\n if (\n index !== undefined &&\n index !== null &&\n (typeof index !== 'number' ||\n index < 0 ||\n index === Number.POSITIVE_INFINITY)\n ) {\n throw new Error('Expected positive finite index')\n }\n\n if (\n parent !== undefined &&\n parent !== null &&\n (!is(parent) || !parent.children)\n ) {\n throw new Error('Expected parent node')\n }\n\n if (\n (parent === undefined || parent === null) !==\n (index === undefined || index === null)\n ) {\n throw new Error('Expected both parent and index')\n }\n\n // @ts-expect-error Looks like a node.\n return node && node.type && typeof node.type === 'string'\n ? Boolean(check.call(context, node, index, parent))\n : false\n }\n )\n\n/**\n * Generate an assertion from a test.\n *\n * Useful if you’re going to test many nodes, for example when creating a\n * utility where something else passes a compatible test.\n *\n * The created function is a bit faster because it expects valid input only:\n * a `node`, `index`, and `parent`.\n *\n * @param test\n * * when nullish, checks if `node` is a `Node`.\n * * when `string`, works like passing `(node) => node.type === test`.\n * * when `function` checks if function passed the node is true.\n * * when `object`, checks that all keys in test are in node, and that they have (strictly) equal values.\n * * when `array`, checks if any one of the subtests pass.\n * @returns\n * An assertion.\n */\nexport const convert =\n /**\n * @type {(\n * (<Kind extends Node>(test: PredicateTest<Kind>) => AssertPredicate<Kind>) &\n * ((test?: Test) => AssertAnything)\n * )}\n */\n (\n /**\n * @param {Test} [test]\n * @returns {AssertAnything}\n */\n function (test) {\n if (test === undefined || test === null) {\n return ok\n }\n\n if (typeof test === 'string') {\n return typeFactory(test)\n }\n\n if (typeof test === 'object') {\n return Array.isArray(test) ? anyFactory(test) : propsFactory(test)\n }\n\n if (typeof test === 'function') {\n return castFactory(test)\n }\n\n throw new Error('Expected function, string, or object as test')\n }\n )\n\n/**\n * @param {Array<string | Props | TestFunctionAnything>} tests\n * @returns {AssertAnything}\n */\nfunction anyFactory(tests) {\n /** @type {Array<AssertAnything>} */\n const checks = []\n let index = -1\n\n while (++index < tests.length) {\n checks[index] = convert(tests[index])\n }\n\n return castFactory(any)\n\n /**\n * @this {unknown}\n * @param {Array<unknown>} parameters\n * @returns {boolean}\n */\n function any(...parameters) {\n let index = -1\n\n while (++index < checks.length) {\n if (checks[index].call(this, ...parameters)) return true\n }\n\n return false\n }\n}\n\n/**\n * Turn an object into a test for a node with a certain fields.\n *\n * @param {Props} check\n * @returns {AssertAnything}\n */\nfunction propsFactory(check) {\n return castFactory(all)\n\n /**\n * @param {Node} node\n * @returns {boolean}\n */\n function all(node) {\n /** @type {string} */\n let key\n\n for (key in check) {\n // @ts-expect-error: hush, it sure works as an index.\n if (node[key] !== check[key]) return false\n }\n\n return true\n }\n}\n\n/**\n * Turn a string into a test for a node with a certain type.\n *\n * @param {string} check\n * @returns {AssertAnything}\n */\nfunction typeFactory(check) {\n return castFactory(type)\n\n /**\n * @param {Node} node\n */\n function type(node) {\n return node && node.type === check\n }\n}\n\n/**\n * Turn a custom test into a test for a node that passes that test.\n *\n * @param {TestFunctionAnything} check\n * @returns {AssertAnything}\n */\nfunction castFactory(check) {\n return assertion\n\n /**\n * @this {unknown}\n * @param {unknown} node\n * @param {Array<unknown>} parameters\n * @returns {boolean}\n */\n function assertion(node, ...parameters) {\n return Boolean(\n node &&\n typeof node === 'object' &&\n 'type' in node &&\n // @ts-expect-error: fine.\n Boolean(check.call(this, node, ...parameters))\n )\n }\n}\n\nfunction ok() {\n return true\n}\n","/**\n * @typedef {import('./lib/index.js').Test} Test\n * @typedef {import('./lib/index.js').TestFunctionAnything} TestFunctionAnything\n * @typedef {import('./lib/index.js').AssertAnything} AssertAnything\n */\n\n/**\n * @template {import('unist').Node} Kind\n * @typedef {import('./lib/index.js').PredicateTest<Kind>} PredicateTest\n */\n\n/**\n * @template {import('unist').Node} Kind\n * @typedef {import('./lib/index.js').TestFunctionPredicate<Kind>} TestFunctionPredicate\n */\n\n/**\n * @template {import('unist').Node} Kind\n * @typedef {import('./lib/index.js').AssertPredicate<Kind>} AssertPredicate\n */\n\nexport {is, convert} from './lib/index.js'\n","/**\n * @param {string} d\n * @returns {string}\n */\nexport function color(d) {\n return '\\u001B[33m' + d + '\\u001B[39m'\n}\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n * @typedef {import('unist-util-is').Test} Test\n */\n\n/**\n * @typedef {boolean | 'skip'} Action\n * Union of the action types.\n *\n * @typedef {number} Index\n * Move to the sibling at `index` next (after node itself is completely\n * traversed).\n *\n * Useful if mutating the tree, such as removing the node the visitor is\n * currently on, or any of its previous siblings.\n * Results less than 0 or greater than or equal to `children.length` stop\n * traversing the parent.\n *\n * @typedef {[(Action | null | undefined | void)?, (Index | null | undefined)?]} ActionTuple\n * List with one or two values, the first an action, the second an index.\n *\n * @typedef {Action | ActionTuple | Index | null | undefined | void} VisitorResult\n * Any value that can be returned from a visitor.\n */\n\n/**\n * @template {Node} [Visited=Node]\n * Visited node type.\n * @template {Parent} [Ancestor=Parent]\n * Ancestor type.\n * @callback Visitor\n * Handle a node (matching `test`, if given).\n *\n * Visitors are free to transform `node`.\n * They can also transform the parent of node (the last of `ancestors`).\n *\n * Replacing `node` itself, if `SKIP` is not returned, still causes its\n * descendants to be walked (which is a bug).\n *\n * When adding or removing previous siblings of `node` (or next siblings, in\n * case of reverse), the `Visitor` should return a new `Index` to specify the\n * sibling to traverse after `node` is traversed.\n * Adding or removing next siblings of `node` (or previous siblings, in case\n * of reverse) is handled as expected without needing to return a new `Index`.\n *\n * Removing the children property of an ancestor still results in them being\n * traversed.\n * @param {Visited} node\n * Found node.\n * @param {Array<Ancestor>} ancestors\n * Ancestors of `node`.\n * @returns {VisitorResult}\n * What to do next.\n *\n * An `Index` is treated as a tuple of `[CONTINUE, Index]`.\n * An `Action` is treated as a tuple of `[Action]`.\n *\n * Passing a tuple back only makes sense if the `Action` is `SKIP`.\n * When the `Action` is `EXIT`, that action can be returned.\n * When the `Action` is `CONTINUE`, `Index` can be returned.\n */\n\n/**\n * @template {Node} [Tree=Node]\n * Tree type.\n * @template {Test} [Check=string]\n * Test type.\n * @typedef {Visitor<import('./complex-types.js').Matches<import('./complex-types.js').InclusiveDescendant<Tree>, Check>, Extract<import('./complex-types.js').InclusiveDescendant<Tree>, Parent>>} BuildVisitor\n * Build a typed `Visitor` function from a tree and a test.\n *\n * It will infer which values are passed as `node` and which as `parents`.\n */\n\nimport {convert} from 'unist-util-is'\nimport {color} from './color.js'\n\n/**\n * Continue traversing as normal.\n */\nexport const CONTINUE = true\n\n/**\n * Stop traversing immediately.\n */\nexport const EXIT = false\n\n/**\n * Do not traverse this node’s children.\n */\nexport const SKIP = 'skip'\n\n/**\n * Visit nodes, with ancestral information.\n *\n * This algorithm performs *depth-first* *tree traversal* in *preorder*\n * (**NLR**) or if `reverse` is given, in *reverse preorder* (**NRL**).\n *\n * You can choose for which nodes `visitor` is called by passing a `test`.\n * For complex tests, you should test yourself in `visitor`, as it will be\n * faster and will have improved type information.\n *\n * Walking the tree is an intensive task.\n * Make use of the return values of the visitor when possible.\n * Instead of walking a tree multiple times, walk it once, use `unist-util-is`\n * to check if a node matches, and then perform different operations.\n *\n * You can change the tree.\n * See `Visitor` for more info.\n *\n * @param tree\n * Tree to traverse.\n * @param test\n * `unist-util-is`-compatible test\n * @param visitor\n * Handle each node.\n * @param reverse\n * Traverse in reverse preorder (NRL) instead of the default preorder (NLR).\n * @returns\n * Nothing.\n */\nexport const visitParents =\n /**\n * @type {(\n * (<Tree extends Node, Check extends Test>(tree: Tree, test: Check, visitor: BuildVisitor<Tree, Check>, reverse?: boolean | null | undefined) => void) &\n * (<Tree extends Node>(tree: Tree, visitor: BuildVisitor<Tree>, reverse?: boolean | null | undefined) => void)\n * )}\n */\n (\n /**\n * @param {Node} tree\n * @param {Test} test\n * @param {Visitor<Node>} visitor\n * @param {boolean | null | undefined} [reverse]\n * @returns {void}\n */\n function (tree, test, visitor, reverse) {\n if (typeof test === 'function' && typeof visitor !== 'function') {\n reverse = visitor\n // @ts-expect-error no visitor given, so `visitor` is test.\n visitor = test\n test = null\n }\n\n const is = convert(test)\n const step = reverse ? -1 : 1\n\n factory(tree, undefined, [])()\n\n /**\n * @param {Node} node\n * @param {number | undefined} index\n * @param {Array<Parent>} parents\n */\n function factory(node, index, parents) {\n /** @type {Record<string, unknown>} */\n // @ts-expect-error: hush\n const value = node && typeof node === 'object' ? node : {}\n\n if (typeof value.type === 'string') {\n const name =\n // `hast`\n typeof value.tagName === 'string'\n ? value.tagName\n : // `xast`\n typeof value.name === 'string'\n ? value.name\n : undefined\n\n Object.defineProperty(visit, 'name', {\n value:\n 'node (' + color(node.type + (name ? '<' + name + '>' : '')) + ')'\n })\n }\n\n return visit\n\n function visit() {\n /** @type {ActionTuple} */\n let result = []\n /** @type {ActionTuple} */\n let subresult\n /** @type {number} */\n let offset\n /** @type {Array<Parent>} */\n let grandparents\n\n if (!test || is(node, index, parents[parents.length - 1] || null)) {\n result = toResult(visitor(node, parents))\n\n if (result[0] === EXIT) {\n return result\n }\n }\n\n // @ts-expect-error looks like a parent.\n if (node.children && result[0] !== SKIP) {\n // @ts-expect-error looks like a parent.\n offset = (reverse ? node.children.length : -1) + step\n // @ts-expect-error looks like a parent.\n grandparents = parents.concat(node)\n\n // @ts-expect-error looks like a parent.\n while (offset > -1 && offset < node.children.length) {\n // @ts-expect-error looks like a parent.\n subresult = factory(node.children[offset], offset, grandparents)()\n\n if (subresult[0] === EXIT) {\n return subresult\n }\n\n offset =\n typeof subresult[1] === 'number' ? subresult[1] : offset + step\n }\n }\n\n return result\n }\n }\n }\n )\n\n/**\n * Turn a return value into a clean result.\n *\n * @param {VisitorResult} value\n * Valid return values from visitors.\n * @returns {ActionTuple}\n * Clean result.\n */\nfunction toResult(value) {\n if (Array.isArray(value)) {\n return value\n }\n\n if (typeof value === 'number') {\n return [CONTINUE, value]\n }\n\n return [value]\n}\n","// Note: types exported from `index.d.ts`\nexport {CONTINUE, EXIT, SKIP, visitParents} from './lib/index.js'\n","/**\n * @typedef {import('unist').Node} Node\n * @typedef {import('unist').Parent} Parent\n * @typedef {import('unist-util-is').Test} Test\n * @typedef {import('unist-util-visit-parents').VisitorResult} VisitorResult\n * @typedef {import('./complex-types.js').Visitor} Visitor\n */\n\nimport {visitParents} from 'unist-util-visit-parents'\n\n/**\n * Visit children of tree which pass test.\n *\n * @param tree\n * Tree to walk\n * @param [test]\n * `unist-util-is`-compatible test\n * @param visitor\n * Function called for nodes that pass `test`.\n * @param reverse\n * Traverse in reverse preorder (NRL) instead of preorder (NLR) (default).\n */\nexport const visit =\n /**\n * @type {(\n * (<Tree extends Node, Check extends Test>(tree: Tree, test: Check, visitor: import('./complex-types.js').BuildVisitor<Tree, Check>, reverse?: boolean) => void) &\n * (<Tree extends Node>(tree: Tree, visitor: import('./complex-types.js').BuildVisitor<Tree>, reverse?: boolean) => void)\n * )}\n */\n (\n /**\n * @param {Node} tree\n * @param {Test} test\n * @param {import('./complex-types.js').Visitor} visitor\n * @param {boolean} [reverse]\n */\n function (tree, test, visitor, reverse) {\n if (typeof test === 'function' && typeof visitor !== 'function') {\n reverse = visitor\n visitor = test\n test = null\n }\n\n visitParents(tree, test, overload, reverse)\n\n /**\n * @param {Node} node\n * @param {Array<Parent>} parents\n */\n function overload(node, parents) {\n const parent = parents[parents.length - 1]\n return visitor(\n node,\n parent ? parent.children.indexOf(node) : null,\n parent\n )\n }\n }\n )\n\nexport {CONTINUE, EXIT, SKIP} from 'unist-util-visit-parents'\n","import { join, parse, extname } from 'path';\nimport { RspackVirtualModulePlugin } from 'rspack-plugin-virtual-module';\nimport {\n type RspressPlugin,\n type RouteMeta,\n RSPRESS_TEMP_DIR,\n normalizePosixPath,\n} from '@rspress/shared';\nimport { uniqBy } from 'lodash';\nimport { remarkCodeToDemo } from './codeToDemo';\nimport { generateId, injectDemoBlockImport } from './utils';\nimport {\n demoBlockComponentPath,\n demoComponentPath,\n staticPath,\n} from './constant';\n\nexport type Options = {\n /**\n * preview in mobile mode or not\n * when isMobile is true, 1. aside will hide. 2. default preview component by iframe\n * @default false\n */\n isMobile?: boolean;\n /**\n * position of the iframe\n * @default 'follow'\n */\n iframePosition?: 'fixed' | 'follow';\n /**\n * whether the demo can open in codesandbox\n * @default false\n * @experimental\n */\n enableCodesandbox?: boolean;\n};\n\ninterface Heading {\n type: string;\n depth?: number;\n children?: ChildNode[];\n}\n\ninterface ChildNode {\n type: 'link' | 'text' | 'inlineCode';\n value: string;\n children?: ChildNode[];\n}\n\n// eslint-disable-next-line import/no-mutable-exports\nexport let routeMeta: RouteMeta[];\nexport const demoRoutes: { path: string }[] = [];\nexport const demoMeta: Record<\n string,\n { id: string; virtualModulePath: string; title: string }[]\n> = {};\n\n/**\n * The plugin is used to preview component.\n */\nexport function pluginPreview(options?: Options): RspressPlugin {\n const isMobile = options?.isMobile ?? false;\n const iframePosition = options?.iframePosition ?? 'follow';\n const enableCodesandbox = options?.enableCodesandbox ?? false;\n const demoRuntimeModule = new RspackVirtualModulePlugin({});\n const globalUIComponents =\n iframePosition === 'fixed'\n ? [join(staticPath, 'global-components', 'Device.tsx')]\n : [];\n const getRouteMeta = () => routeMeta;\n return {\n name: '@rspress/plugin-preview',\n config(config) {\n config.markdown = config.markdown || {};\n config.markdown.mdxRs = false;\n return config;\n },\n addPages(_config, _isProd) {\n return [\n {\n routePath: '/~demo/:id',\n content: `---\npageType: \"blank\"\n---\n\nimport Demo from ${JSON.stringify(demoComponentPath)}\n\n<Demo iframePosition=\"${iframePosition}\"/>\n `,\n },\n ];\n },\n async routeGenerated(routes: RouteMeta[]) {\n // init routeMeta\n routeMeta = routes;\n\n const files = routes.map(route => route.absolutePath);\n // Write the demo code ahead of time\n // Fix: rspack build error because demo file is not exist, probably the demo file was written in rspack build process?\n await Promise.all(\n files.map(async (filepath, _index) => {\n const isMdxFile = /\\.mdx?$/.test(filepath);\n if (!isMdxFile) {\n return;\n }\n const { createProcessor } = await import('@mdx-js/mdx');\n const { visit } = await import('unist-util-visit');\n const { default: fs } = await import('@modern-js/utils/fs-extra');\n const { default: remarkGFM } = await import('remark-gfm');\n let title = parse(filepath).name;\n try {\n const processor = createProcessor({\n format: extname(filepath).slice(1) as 'mdx' | 'md',\n remarkPlugins: [remarkGFM],\n });\n const source = await fs.readFile(filepath, 'utf-8');\n const ast = processor.parse(source);\n let index = 1;\n const { pageName } = routeMeta.find(\n meta =>\n normalizePosixPath(meta.absolutePath) ===\n normalizePosixPath(filepath),\n )!;\n\n const registerDemo = (\n demoId: string,\n demoPath: string,\n isMobileMode: boolean,\n ) => {\n if (isMobileMode) {\n // only add demoMeta in mobile mode\n demoMeta[filepath] = demoMeta[filepath] ?? [];\n const isExist = demoMeta[filepath].find(\n item => item.id === demoId,\n );\n if (!isExist) {\n demoMeta[filepath].push({\n id: demoId,\n title,\n virtualModulePath: demoPath,\n });\n }\n }\n };\n visit(ast, 'heading', (node: Heading) => {\n if (node.depth === 1) {\n if (node.children) {\n title = node.children[0].value;\n }\n }\n });\n\n visit(ast, 'mdxJsxFlowElement', (node: any) => {\n if (node.name === 'code') {\n const src = node.attributes.find(\n (attr: { name: string; value: string }) =>\n attr.name === 'src',\n )?.value;\n const isMobileMode =\n node.attributes.find(\n (attr: { name: string; value: boolean }) =>\n attr.name === 'isMobile',\n )?.value ?? isMobile;\n if (!src) {\n return;\n }\n const id = generateId(pageName, index++);\n registerDemo(id, src, isMobileMode);\n }\n });\n\n visit(ast, 'code', (node: any) => {\n if (node.lang === 'jsx' || node.lang === 'tsx') {\n const { value } = node;\n const isPure = node?.meta?.includes('pure');\n\n // do not anything for pure mode\n if (isPure) {\n return;\n }\n\n // every code block can change their preview mode by meta\n const isMobileMode =\n node?.meta?.includes('mobile') ||\n (!node?.meta?.includes('web') && isMobile);\n\n const { pageName } = routeMeta.find(\n meta =>\n normalizePosixPath(meta.absolutePath) ===\n normalizePosixPath(filepath),\n )!;\n const id = generateId(pageName, index++);\n\n const demoDir = join(\n process.cwd(),\n 'node_modules',\n RSPRESS_TEMP_DIR,\n `virtual-demo`,\n );\n\n const virtualModulePath = join(demoDir, `${id}.tsx`);\n registerDemo(id, virtualModulePath, isMobileMode);\n\n fs.ensureDirSync(join(demoDir));\n fs.writeFileSync(\n virtualModulePath,\n injectDemoBlockImport(value, demoBlockComponentPath),\n );\n }\n });\n } catch (e) {\n console.error(e);\n throw e;\n }\n }),\n );\n /**\n * expect the meta of each demo file is like this:\n * {\n * id,\n * component,\n * }\n */\n const virtualMeta = `\n ${files\n .map((filepath, index) => {\n return `import Route${index} from '${filepath}?meta';`;\n })\n .join('\\n')}\n export const demos = [${files\n .map((_, index) => `Route${index}`)\n .flat()\n .join(',')}];\n `;\n demoRuntimeModule.writeModule('virtual-meta', virtualMeta);\n },\n builderConfig: {\n tools: {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment, @typescript-eslint/prefer-ts-expect-error\n // @ts-ignore\n rspack: {\n plugins: [demoRuntimeModule],\n },\n bundlerChain(chain) {\n chain.module\n .rule('Raw')\n .resourceQuery(/raw/)\n .type('asset/source')\n .end()\n .rule('MDX')\n .oneOf('MDXMeta')\n .before('MDXCompile')\n .resourceQuery(/meta/)\n .use('mdx-meta-loader')\n .loader(join(__dirname, '../mdx-meta-loader.cjs'))\n .end();\n\n chain.resolve.extensions.prepend('.md').prepend('.mdx');\n },\n },\n },\n markdown: {\n remarkPlugins: [\n [\n remarkCodeToDemo,\n { isMobile, getRouteMeta, iframePosition, enableCodesandbox },\n ],\n ],\n globalComponents: [\n join(staticPath, 'global-components', 'Container.tsx'),\n ],\n },\n globalUIComponents,\n globalStyles: join(\n staticPath,\n 'global-styles',\n `${isMobile ? 'mobile' : 'web'}.css`,\n ),\n addSSGRoutes() {\n if (iframePosition === 'fixed') {\n const normalizeRoutes = demoRoutes.map(({ path: item }) => {\n const fragments = item.split('/').filter(Boolean);\n const demoId = fragments.pop()?.replace(/_(\\d+)$/, '');\n return { path: `/${fragments.join('/')}/${demoId}` };\n });\n // Unique the routes accrodint to the path\n return uniqBy(normalizeRoutes, 'path');\n }\n return demoRoutes;\n },\n };\n}\n\nexport { normalizeId } from './utils';\n","import { join, resolve } from 'path';\nimport { visit } from 'unist-util-visit';\nimport fs from '@modern-js/utils/fs-extra';\nimport {\n RSPRESS_TEMP_DIR,\n normalizePosixPath,\n type RouteMeta,\n} from '@rspress/shared';\nimport type { Plugin } from 'unified';\nimport type { Root } from 'mdast';\nimport type { MdxjsEsm } from 'mdast-util-mdxjs-esm';\nimport { injectDemoBlockImport, generateId } from './utils';\nimport { demoBlockComponentPath } from './constant';\nimport { demoRoutes } from '.';\n\n// FIXME: remove it\nconst json = JSON.parse(\n fs.readFileSync(resolve(process.cwd(), './package.json'), 'utf8'),\n);\n\n/**\n * remark plugin to transform code to demo\n */\nexport const remarkCodeToDemo: Plugin<\n [\n {\n isMobile: boolean;\n getRouteMeta: () => RouteMeta[];\n iframePosition: 'fixed' | 'follow';\n enableCodesandbox: boolean;\n },\n ],\n Root\n> = ({ isMobile, getRouteMeta, iframePosition, enableCodesandbox }) => {\n const routeMeta = getRouteMeta();\n\n return (tree, vfile) => {\n const demos: MdxjsEsm[] = [];\n const route = routeMeta.find(\n meta =>\n normalizePosixPath(meta.absolutePath) ===\n normalizePosixPath(vfile.path || vfile.history[0]),\n );\n if (!route) {\n return;\n }\n const { pageName } = route;\n let index = 1;\n let externalDemoIndex = 0;\n\n function constructDemoNode(\n demoId: string,\n demoPath: string,\n currentNode: any,\n isMobileMode: boolean,\n // Only for external demo\n externalDemoIndex?: number,\n ) {\n const demoRoute = `/~demo/${demoId}`;\n if (isMobileMode) {\n // only add demoRoutes in mobile mode\n demoRoutes.push({\n path: demoRoute,\n });\n } else {\n demos.push(getASTNodeImport(`Demo${demoId}`, demoPath));\n }\n\n // get external demo content\n const tempVar = `externalDemoContent${externalDemoIndex}`;\n if (externalDemoIndex !== undefined) {\n demos.push(getASTNodeImport(tempVar, `${demoPath}?raw`));\n }\n\n if (isMobileMode && iframePosition === 'fixed') {\n // Only show the code block\n externalDemoIndex !== undefined &&\n Object.assign(currentNode, getExternalDemoContent(tempVar));\n } else {\n // Use container to show the code and view\n Object.assign(currentNode, {\n type: 'mdxJsxFlowElement',\n name: 'Container',\n attributes: [\n {\n type: 'mdxJsxAttribute',\n name: 'isMobile',\n value: isMobileMode,\n },\n {\n type: 'mdxJsxAttribute',\n name: 'url',\n value: demoRoute,\n },\n {\n type: 'mdxJsxAttribute',\n name: 'content',\n value: currentNode.value,\n },\n {\n type: 'mdxJsxAttribute',\n name: 'packageName',\n value: json.name,\n },\n {\n type: 'mdxJsxAttribute',\n name: 'enableCodesandbox',\n value: enableCodesandbox,\n },\n ],\n children: [\n externalDemoIndex === undefined\n ? {\n ...currentNode,\n hasVisited: true,\n }\n : getExternalDemoContent(tempVar),\n isMobileMode\n ? {\n type: 'mdxJsxFlowElement',\n name: null,\n }\n : {\n type: 'mdxJsxFlowElement',\n name: `Demo${demoId}`,\n },\n ],\n });\n }\n }\n\n // 1. External demo , use <code src=\"xxx\" /> to declare demo\n tree.children.forEach((node: any) => {\n if (node.type === 'mdxJsxFlowElement' && node.name === 'code') {\n const src = node.attributes.find(\n (attr: { name: string; value: string }) => attr.name === 'src',\n )?.value;\n const isMobileMode =\n node.attributes.find(\n (attr: { name: string; value: boolean }) =>\n attr.name === 'isMobile',\n )?.value ?? isMobile;\n if (!src) {\n return;\n }\n const id = generateId(pageName, index++);\n constructDemoNode(id, src, node, isMobileMode, externalDemoIndex++);\n }\n });\n\n // 2. Internal demo, use ```j/tsx to declare demo\n visit(tree, 'code', node => {\n // hasVisited is a custom property\n if ('hasVisited' in node) {\n return;\n }\n\n if (node.lang === 'jsx' || node.lang === 'tsx') {\n const value = injectDemoBlockImport(node.value, demoBlockComponentPath);\n\n const isPure = node?.meta?.includes('pure');\n\n // do nothing for pure mode\n if (isPure) {\n return;\n }\n\n // every code block can change their preview mode by meta\n const isMobileMode =\n node?.meta?.includes('mobile') ||\n (!node?.meta?.includes('web') && isMobile);\n\n const demoDir = join(\n process.cwd(),\n 'node_modules',\n RSPRESS_TEMP_DIR,\n `virtual-demo`,\n );\n const id = generateId(pageName, index++);\n const virtualModulePath = join(demoDir, `${id}.tsx`);\n fs.ensureDirSync(join(demoDir));\n // Only when the content of the file changes, the file will be written\n // Avoid to trigger the hmr indefinitely\n if (fs.existsSync(virtualModulePath)) {\n const content = fs.readFileSync(virtualModulePath, 'utf-8');\n if (content !== value) {\n fs.writeFileSync(virtualModulePath, value);\n }\n }\n constructDemoNode(id, virtualModulePath, node, isMobileMode);\n }\n });\n\n tree.children.unshift(...demos);\n };\n};\n\nconst getASTNodeImport = (name: string, from: string) =>\n ({\n type: 'mdxjsEsm',\n value: `import ${name} from ${JSON.stringify(from)}`,\n data: {\n estree: {\n type: 'Program',\n sourceType: 'module',\n body: [\n {\n type: 'ImportDeclaration',\n specifiers: [\n {\n type: 'ImportDefaultSpecifier',\n local: { type: 'Identifier', name },\n },\n ],\n source: {\n type: 'Literal',\n value: from,\n raw: `${JSON.stringify(from)}`,\n },\n },\n ],\n },\n },\n } as MdxjsEsm);\n\nconst getExternalDemoContent = (tempVar: string) => ({\n type: 'mdxJsxFlowElement',\n name: 'pre',\n children: [\n {\n type: 'mdxJsxFlowElement',\n name: 'code',\n attributes: [\n {\n type: 'mdxJsxAttribute',\n name: 'className',\n value: 'language-tsx',\n },\n {\n type: 'mdxJsxAttribute',\n name: 'children',\n value: {\n type: 'mdxJsxExpressionAttribute',\n value: tempVar,\n data: {\n estree: {\n type: 'Program',\n body: [\n {\n type: 'ExpressionStatement',\n expression: {\n type: 'Identifier',\n name: tempVar,\n },\n },\n ],\n },\n },\n },\n },\n ],\n },\n ],\n});\n","/**\n * Converts a string to a valid variable name. If the string is already a valid variable name, returns the original string.\n * @param str - The string to convert.\n * @returns The converted string.\n */\nexport const toValidVarName = (str: string): string => {\n // Check if the string is a valid variable name\n if (/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(str)) {\n return str; // If it is a valid variable name, return the original string\n } else {\n // If it is not a valid variable name, convert it to a valid variable name\n return str.replace(/[^0-9a-zA-Z_$]/g, '_').replace(/^([0-9])/, '_$1');\n }\n};\n\nexport const generateId = (pageName: string, index: number) => {\n return `_${toValidVarName(pageName)}_${index}`;\n};\n\n/**\n * remove .html extension and validate\n * @param routePath id from pathname\n * @returns normalized id\n */\nexport const normalizeId = (routePath: string) => {\n const result = routePath.replace(/\\.(.*)?$/, '');\n return toValidVarName(result);\n};\n\nexport const injectDemoBlockImport = (str: string, path: string): string => {\n return `\n import DemoBlock from '${path}';\n ${str}\n `;\n};\n","import path from 'path';\n\nexport const staticPath = path.join(__dirname, '..', 'static');\n\nexport const demoComponentPath = path.join(\n __dirname,\n '..',\n 'dist',\n 'virtual-demo.js',\n);\n\nexport const demoBlockComponentPath = path.join(\n staticPath,\n 'global-components',\n 'DemoBlock.tsx',\n);\n"]}
|
package/dist/utils.d.ts
ADDED
@@ -0,0 +1,16 @@
|
|
1
|
+
/**
|
2
|
+
* Converts a string to a valid variable name. If the string is already a valid variable name, returns the original string.
|
3
|
+
* @param str - The string to convert.
|
4
|
+
* @returns The converted string.
|
5
|
+
*/
|
6
|
+
declare const toValidVarName: (str: string) => string;
|
7
|
+
declare const generateId: (pageName: string, index: number) => string;
|
8
|
+
/**
|
9
|
+
* remove .html extension and validate
|
10
|
+
* @param routePath id from pathname
|
11
|
+
* @returns normalized id
|
12
|
+
*/
|
13
|
+
declare const normalizeId: (routePath: string) => string;
|
14
|
+
declare const injectDemoBlockImport: (str: string, path: string) => string;
|
15
|
+
|
16
|
+
export { generateId, injectDemoBlockImport, normalizeId, toValidVarName };
|
package/dist/utils.js
ADDED
@@ -0,0 +1,57 @@
|
|
1
|
+
"use strict";
|
2
|
+
var __defProp = Object.defineProperty;
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
6
|
+
var __export = (target, all) => {
|
7
|
+
for (var name in all)
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
9
|
+
};
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
12
|
+
for (let key of __getOwnPropNames(from))
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
15
|
+
}
|
16
|
+
return to;
|
17
|
+
};
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
19
|
+
|
20
|
+
// src/utils.ts
|
21
|
+
var utils_exports = {};
|
22
|
+
__export(utils_exports, {
|
23
|
+
generateId: () => generateId,
|
24
|
+
injectDemoBlockImport: () => injectDemoBlockImport,
|
25
|
+
normalizeId: () => normalizeId,
|
26
|
+
toValidVarName: () => toValidVarName
|
27
|
+
});
|
28
|
+
module.exports = __toCommonJS(utils_exports);
|
29
|
+
var toValidVarName = (str) => {
|
30
|
+
if (/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(str)) {
|
31
|
+
return str;
|
32
|
+
} else {
|
33
|
+
return str.replace(/[^0-9a-zA-Z_$]/g, "_").replace(/^([0-9])/, "_$1");
|
34
|
+
}
|
35
|
+
};
|
36
|
+
var generateId = (pageName, index) => {
|
37
|
+
return `_${toValidVarName(pageName)}_${index}`;
|
38
|
+
};
|
39
|
+
var normalizeId = (routePath) => {
|
40
|
+
const result = routePath.replace(/\.(.*)?$/, "");
|
41
|
+
return toValidVarName(result);
|
42
|
+
};
|
43
|
+
var injectDemoBlockImport = (str, path) => {
|
44
|
+
return `
|
45
|
+
import DemoBlock from '${path}';
|
46
|
+
${str}
|
47
|
+
`;
|
48
|
+
};
|
49
|
+
// Annotate the CommonJS export names for ESM import in node:
|
50
|
+
0 && (module.exports = {
|
51
|
+
generateId,
|
52
|
+
injectDemoBlockImport,
|
53
|
+
normalizeId,
|
54
|
+
toValidVarName
|
55
|
+
});
|
56
|
+
|
57
|
+
//# sourceMappingURL=utils.js.map
|
@@ -0,0 +1 @@
|
|
1
|
+
{"version":3,"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKO,IAAM,iBAAiB,CAAC,QAAwB;AAErD,MAAI,6BAA6B,KAAK,GAAG,GAAG;AAC1C,WAAO;AAAA,EACT,OAAO;AAEL,WAAO,IAAI,QAAQ,mBAAmB,GAAG,EAAE,QAAQ,YAAY,KAAK;AAAA,EACtE;AACF;AAEO,IAAM,aAAa,CAAC,UAAkB,UAAkB;AAC7D,SAAO,IAAI,eAAe,QAAQ,CAAC,IAAI,KAAK;AAC9C;AAOO,IAAM,cAAc,CAAC,cAAsB;AAChD,QAAM,SAAS,UAAU,QAAQ,YAAY,EAAE;AAC/C,SAAO,eAAe,MAAM;AAC9B;AAEO,IAAM,wBAAwB,CAAC,KAAa,SAAyB;AAC1E,SAAO;AAAA,6BACoB,IAAI;AAAA,MAC3B,GAAG;AAAA;AAET;","names":[],"sources":["../src/utils.ts"],"sourcesContent":["/**\n * Converts a string to a valid variable name. If the string is already a valid variable name, returns the original string.\n * @param str - The string to convert.\n * @returns The converted string.\n */\nexport const toValidVarName = (str: string): string => {\n // Check if the string is a valid variable name\n if (/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(str)) {\n return str; // If it is a valid variable name, return the original string\n } else {\n // If it is not a valid variable name, convert it to a valid variable name\n return str.replace(/[^0-9a-zA-Z_$]/g, '_').replace(/^([0-9])/, '_$1');\n }\n};\n\nexport const generateId = (pageName: string, index: number) => {\n return `_${toValidVarName(pageName)}_${index}`;\n};\n\n/**\n * remove .html extension and validate\n * @param routePath id from pathname\n * @returns normalized id\n */\nexport const normalizeId = (routePath: string) => {\n const result = routePath.replace(/\\.(.*)?$/, '');\n return toValidVarName(result);\n};\n\nexport const injectDemoBlockImport = (str: string, path: string): string => {\n return `\n import DemoBlock from '${path}';\n ${str}\n `;\n};\n"]}
|
package/dist/virtual-demo.js
CHANGED
@@ -53,10 +53,10 @@ style_inject_es_default(css_248z);
|
|
53
53
|
import { jsx, jsxs } from "react/jsx-runtime";
|
54
54
|
function Demo(props) {
|
55
55
|
const { pathname } = useLocation();
|
56
|
-
const
|
57
|
-
const normalizedId = normalizeId(
|
56
|
+
const pureDemoPath = pathname.split("/").filter(Boolean).slice(1)?.join("/");
|
57
|
+
const normalizedId = normalizeId(pureDemoPath || "");
|
58
58
|
if (props.iframePosition === "fixed") {
|
59
|
-
const renderDemos = demos.flat().filter((item) => new RegExp(
|
59
|
+
const renderDemos = demos.flat().filter((item) => new RegExp(`${normalizedId}_\\d+`).test(item.id));
|
60
60
|
return renderDemos.length > 0 ? /* @__PURE__ */ jsx(NoSSR, { children: /* @__PURE__ */ jsxs("div", { className: "preview-container", children: [
|
61
61
|
/* @__PURE__ */ jsx("div", { className: "preview-nav", children: renderDemos[0].title }),
|
62
62
|
renderDemos.map((renderDemo) => {
|
package/package.json
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
{
|
2
2
|
"name": "@rspress/plugin-preview",
|
3
|
-
"version": "1.
|
3
|
+
"version": "1.2.0",
|
4
4
|
"description": "A plugin for rspress to preview the code block in markdown/mdx file.",
|
5
5
|
"bugs": "https://github.com/web-infra-dev/rspress/issues",
|
6
6
|
"repository": {
|
@@ -26,11 +26,13 @@
|
|
26
26
|
"remark-gfm": "3.0.1",
|
27
27
|
"rspack-plugin-virtual-module": "0.1.12",
|
28
28
|
"codesandbox": "2.2.3",
|
29
|
-
"
|
29
|
+
"lodash": "4.17.21",
|
30
|
+
"@rspress/shared": "1.2.0"
|
30
31
|
},
|
31
32
|
"devDependencies": {
|
32
33
|
"@types/mdast": "^3.0.10",
|
33
34
|
"@types/node": "^18.11.17",
|
35
|
+
"@types/lodash": "4.14.200",
|
34
36
|
"@types/react": "^18",
|
35
37
|
"@types/react-dom": "^18",
|
36
38
|
"mdast-util-mdxjs-esm": "^1.3.0",
|
@@ -1,6 +1,7 @@
|
|
1
1
|
import { usePageData, withBase } from '@rspress/core/runtime';
|
2
2
|
import { demos } from 'virtual-meta';
|
3
3
|
import { useCallback, useEffect, useState } from 'react';
|
4
|
+
import { normalizeId } from '../../dist/utils';
|
4
5
|
import MobileOperation from './common/mobile-operation';
|
5
6
|
import './Device.scss';
|
6
7
|
|
@@ -12,22 +13,17 @@ export default () => {
|
|
12
13
|
// Do nothing in ssr
|
13
14
|
return '';
|
14
15
|
};
|
15
|
-
const removeLeadingSlash = (url: string) => {
|
16
|
-
return url.charAt(0) === '/' ? url.slice(1) : url;
|
17
|
-
};
|
18
|
-
|
19
|
-
const getPageKey = (route: string) => {
|
20
|
-
const cleanRoute = removeLeadingSlash(route);
|
21
|
-
return cleanRoute.replace(/\//g, '_').replace(/\.[^.]+$/, '') || 'index';
|
22
|
-
};
|
23
16
|
const { page } = usePageData();
|
24
|
-
|
17
|
+
|
18
|
+
const pageName = `_${normalizeId(page.pagePath)}`;
|
25
19
|
const url = `~demo/${pageName}`;
|
26
20
|
const haveDemos =
|
27
21
|
demos.flat().filter(item => new RegExp(`${pageName}_\\d+`).test(item.id))
|
28
22
|
.length > 0;
|
23
|
+
const initialInnerWidth =
|
24
|
+
typeof window !== 'undefined' ? window.innerWidth : 0;
|
29
25
|
const [asideWidth, setAsideWidth] = useState('0px');
|
30
|
-
const [innerWidth, setInnerWidth] = useState(
|
26
|
+
const [innerWidth, setInnerWidth] = useState(initialInnerWidth);
|
31
27
|
const [iframeKey, setIframeKey] = useState(0);
|
32
28
|
const refresh = useCallback(() => {
|
33
29
|
setIframeKey(Math.random());
|