dumi 2.4.36 → 2.4.37

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,11 +1,14 @@
1
- import { useDemo, useLiveDemo, useParams } from 'dumi';
1
+ import { useDemo, useLiveDemo, useLocation, useParams } from 'dumi';
2
2
  import { createElement, useEffect } from 'react';
3
3
  import { useRenderer } from "../../theme-api/useRenderer";
4
4
  import "./index.less";
5
5
  var DemoRenderPage = function DemoRenderPage() {
6
6
  var params = useParams();
7
+ var _useLocation = useLocation(),
8
+ search = _useLocation.search;
7
9
  var id = params.id;
8
- var demo = useDemo(id);
10
+ var routeId = new URLSearchParams(search).get('routeId') || undefined;
11
+ var demo = useDemo(id, undefined, undefined, routeId);
9
12
  var _useRenderer = useRenderer({
10
13
  id: id,
11
14
  component: demo.component,
@@ -34,12 +34,13 @@ var InternalDumiDemo = function InternalDumiDemo(props) {
34
34
  return demoNode;
35
35
  }
36
36
  var isHashRoute = historyType === 'hash';
37
+ var routeQuery = demo.routeId ? "?routeId=".concat(encodeURIComponent(demo.routeId)) : '';
37
38
  return /*#__PURE__*/React.createElement(Previewer, _extends({
38
39
  asset: asset,
39
40
  demoUrl:
40
41
  // allow user override demoUrl by frontmatter
41
42
  props.previewerProps.demoUrl || // when use hash route, browser can automatically handle relative paths starting with #
42
- "".concat(isHashRoute ? "#" : '').concat(basename).concat(SP_ROUTE_PREFIX, "demos/").concat(props.demo.id)
43
+ "".concat(isHashRoute ? "#" : '').concat(basename).concat(SP_ROUTE_PREFIX, "demos/").concat(props.demo.id).concat(routeQuery)
43
44
  }, props.previewerProps), props.previewerProps.iframe ? null : demoNode);
44
45
  };
45
46
  export var DumiDemo = /*#__PURE__*/React.memo(InternalDumiDemo, function (prev, next) {
@@ -1,5 +1,6 @@
1
1
  import type { IApi } from '../types';
2
2
  export declare const TABS_META_PATH = "dumi/meta/tabs.ts";
3
3
  export declare const ATOMS_META_PATH = "dumi/meta/atoms.ts";
4
+ export declare const DEMO_INDEX_META_PATH = "dumi/meta/demoIndex.ts";
4
5
  export default _default;
5
6
  declare function _default(api: IApi): void;
@@ -30,6 +30,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  var meta_exports = {};
31
31
  __export(meta_exports, {
32
32
  ATOMS_META_PATH: () => ATOMS_META_PATH,
33
+ DEMO_INDEX_META_PATH: () => DEMO_INDEX_META_PATH,
33
34
  TABS_META_PATH: () => TABS_META_PATH,
34
35
  default: () => meta_default
35
36
  });
@@ -40,6 +41,7 @@ var import_plugin_utils = require("umi/plugin-utils");
40
41
  var import_tabs = require("./tabs");
41
42
  var TABS_META_PATH = "dumi/meta/tabs.ts";
42
43
  var ATOMS_META_PATH = "dumi/meta/atoms.ts";
44
+ var DEMO_INDEX_META_PATH = "dumi/meta/demoIndex.ts";
43
45
  var meta_default = (api) => {
44
46
  const metaFiles = [];
45
47
  api.register({
@@ -71,9 +73,11 @@ var meta_default = (api) => {
71
73
  key: "dumi.modifyMetaFiles",
72
74
  initialValue: JSON.parse(JSON.stringify(metaFiles))
73
75
  });
76
+ const useUtoopackDemoHMR = api.env === "development" && Boolean(api.config.utoopack);
74
77
  parsedMetaFiles.forEach((metaFile) => {
75
78
  metaFile.isMarkdown = metaFile.file.endsWith(".md");
76
- metaFile.loadDemoIndex = metaFile.isMarkdown && !(api.env === "development" && Boolean(api.config.utoopack));
79
+ metaFile.loadDemoIndex = metaFile.isMarkdown && !useUtoopackDemoHMR;
80
+ metaFile.loadDemoIndexMap = metaFile.isMarkdown && useUtoopackDemoHMR;
77
81
  });
78
82
  api.writeTmpFile({
79
83
  noPluginDir: true,
@@ -94,6 +98,14 @@ var meta_default = (api) => {
94
98
  }
95
99
  }
96
100
  });
101
+ api.writeTmpFile({
102
+ noPluginDir: true,
103
+ path: DEMO_INDEX_META_PATH,
104
+ tplPath: require.resolve("../templates/meta/demoIndex.ts.tpl"),
105
+ context: {
106
+ metaFiles: parsedMetaFiles
107
+ }
108
+ });
97
109
  api.writeTmpFile({
98
110
  noPluginDir: true,
99
111
  path: "dumi/meta/runtime.ts",
@@ -119,5 +131,6 @@ var meta_default = (api) => {
119
131
  // Annotate the CommonJS export names for ESM import in node:
120
132
  0 && (module.exports = {
121
133
  ATOMS_META_PATH,
134
+ DEMO_INDEX_META_PATH,
122
135
  TABS_META_PATH
123
136
  });
@@ -53,6 +53,17 @@ function getDemoSourceFiles(demos = []) {
53
53
  function isRelativePath(path2) {
54
54
  return /^\.{1,2}(?!\w)/.test(path2);
55
55
  }
56
+ function normalizeRouteFile(file) {
57
+ return (0, import_plugin_utils.winPath)(file).replace(/\.(mdx?)\.js$/, ".$1");
58
+ }
59
+ function getRouteId(opts, fileAbsPath) {
60
+ const normalizedFile = normalizeRouteFile(fileAbsPath);
61
+ const route = Object.values(opts.routes ?? {}).find((item) => {
62
+ const routeFile = item.file || item.__absFile;
63
+ return routeFile && normalizeRouteFile(routeFile) === normalizedFile;
64
+ });
65
+ return route == null ? void 0 : route.id;
66
+ }
56
67
  function emitDefault(opts, ret) {
57
68
  const { frontmatter, demos } = ret.meta;
58
69
  const isTabContent = (0, import_tabs.isTabRouteFile)(this.resourcePath);
@@ -133,6 +144,7 @@ function emitDemo(opts, ret) {
133
144
  }).filter((item) => item !== void 0)
134
145
  );
135
146
  }, []);
147
+ const routeId = getRouteId(opts, this.resourcePath);
136
148
  return import_plugin_utils.Mustache.render(
137
149
  `import React from 'react';
138
150
  import '${(0, import_plugin_utils.winPath)(this.resourcePath)}?watch=parent';
@@ -146,6 +158,9 @@ export const demos = {
146
158
  component: {{{component}}},
147
159
  {{/component}}
148
160
  asset: {{{renderAsset}}},
161
+ {{#routeId}}
162
+ routeId: '{{{routeId}}}',
163
+ {{/routeId}}
149
164
  context: {{{renderContext}}},
150
165
  renderOpts: {{{renderRenderOpts}}},
151
166
  },
@@ -154,6 +169,7 @@ export const demos = {
154
169
  {
155
170
  demos,
156
171
  dedupedDemosDeps,
172
+ routeId,
157
173
  renderAsset: function renderAsset() {
158
174
  if (!("asset" in this))
159
175
  return "null";
@@ -291,7 +307,9 @@ function emitText(opts, ret) {
291
307
  function emit(opts, ret) {
292
308
  const { demos, embeds } = ret.meta;
293
309
  embeds.forEach((file) => this.addDependency(file));
294
- getDemoSourceFiles(demos).forEach((file) => this.addDependency(file));
310
+ if (opts.mode !== "demo-index") {
311
+ getDemoSourceFiles(demos).forEach((file) => this.addDependency(file));
312
+ }
295
313
  if (this.resourceQuery.includes("watch=parent"))
296
314
  return null;
297
315
  switch (opts.mode) {
@@ -320,7 +338,7 @@ function mdLoader(content) {
320
338
  var _a, _b, _c;
321
339
  let opts = this.getOptions();
322
340
  const loaderContextPath = opts[import_utoopackLoaders.UTOOPACK_LOADER_CTX_KEY];
323
- const useUtoopackDemoHMR = process.env.NODE_ENV === "development" && Boolean(loaderContextPath);
341
+ const useUtoopackDemoHMR = process.env.NODE_ENV !== "production" && Boolean(loaderContextPath);
324
342
  if (loaderContextPath) {
325
343
  const ctx = require(loaderContextPath);
326
344
  if (!((_a = opts.techStacks) == null ? void 0 : _a.length)) {
@@ -0,0 +1,10 @@
1
+ export const demoIndexMap = {
2
+ {{#metaFiles}}
3
+ {{#loadDemoIndexMap}}
4
+ '{{{id}}}': () =>
5
+ import('{{{file}}}?type=demo-index').then(
6
+ ({ demoIndex }) => demoIndex,
7
+ ),
8
+ {{/loadDemoIndexMap}}
9
+ {{/metaFiles}}
10
+ };
@@ -34,21 +34,53 @@ export function use<T>(promise: ReactPromise<T>): T {
34
34
  }
35
35
  }
36
36
 
37
- const demoIdMap = Object.keys(filesMeta).reduce((total, current) => {
38
- if (filesMeta[current].demoIndex) {
39
- const { ids, getter } = filesMeta[current].demoIndex;
37
+ type DemoGetter = () => Promise<{ demos: Record<string, IDemoData> }>;
38
+ type DemoIndex = {
39
+ ids: string[];
40
+ getter: DemoGetter;
41
+ };
42
+ type DemoIndexGetter = () => Promise<DemoIndex>;
40
43
 
41
- ids.forEach((id) => {
42
- total[id] = getter;
43
- });
44
- }
44
+ const demoIndexes = Object.entries(filesMeta)
45
+ .map(([id, meta]) => ({
46
+ id,
47
+ demoIndex: meta.demoIndex,
48
+ }))
49
+ .filter(
50
+ (item): item is { id: string; demoIndex: DemoIndex } =>
51
+ Boolean(item.demoIndex),
52
+ );
45
53
 
46
- return total;
47
- }, {});
54
+ const demoIdMap = demoIndexes.reduce<Record<string, DemoGetter>>(
55
+ (total, { demoIndex }) => {
56
+ if (demoIndex) {
57
+ const { ids, getter } = demoIndex;
48
58
 
49
- type DemoGetter = () => Promise<{ demos: Record<string, IDemoData> }>;
59
+ ids.forEach((id) => {
60
+ total[id] = getter;
61
+ });
62
+ }
63
+
64
+ return total;
65
+ },
66
+ {},
67
+ );
50
68
 
51
69
  const demosCache = new Map<string, Promise<IDemoData | undefined>>();
70
+ let demoIndexMapPromise:
71
+ | Promise<Record<string, DemoIndexGetter | undefined>>
72
+ | undefined;
73
+
74
+ function loadDemoIndexMap() {
75
+ if (!demoIndexMapPromise) {
76
+ demoIndexMapPromise = import('./demoIndex').then(
77
+ ({ demoIndexMap }) =>
78
+ demoIndexMap as Record<string, DemoIndexGetter | undefined>,
79
+ );
80
+ }
81
+
82
+ return demoIndexMapPromise;
83
+ }
52
84
 
53
85
  /**
54
86
  * expand context for source omit extension
@@ -67,6 +99,65 @@ function expandDemoContext(context?: IDemoData['context']) {
67
99
  }
68
100
  }
69
101
 
102
+ function getDemoIdCandidates(id: string) {
103
+ const ids = [id];
104
+ const localeLessId = id.replace(/-[a-z]{2}(?:-[A-Z]{2})?$/, '');
105
+
106
+ if (localeLessId !== id) {
107
+ ids.push(localeLessId);
108
+ }
109
+
110
+ return ids;
111
+ }
112
+
113
+ async function getDemoFromDemoIndex(
114
+ id: string,
115
+ demoIndexGetter: DemoIndexGetter,
116
+ ) {
117
+ const demoIndex = await demoIndexGetter();
118
+ const demoId = getDemoIdCandidates(id).find((candidate) =>
119
+ demoIndex.ids.includes(candidate),
120
+ );
121
+ const getter = demoId ? demoIndex.getter : undefined;
122
+
123
+ if (!getter) return undefined;
124
+
125
+ demoIdMap[id] = getter;
126
+ const { demos } = await getter();
127
+ const demo = demos[id] ?? demos[demoId!];
128
+
129
+ if (!demo) return undefined;
130
+
131
+ expandDemoContext(demo.context);
132
+ return demo;
133
+ }
134
+
135
+ async function getDemoFromRouteIndex(id: string, routeId: string) {
136
+ const demoIndexMap = await loadDemoIndexMap();
137
+ const demoIndexGetter = demoIndexMap[routeId];
138
+
139
+ if (!demoIndexGetter) return getDemoFromIndexMap(id);
140
+
141
+ return (
142
+ (await getDemoFromDemoIndex(id, demoIndexGetter)) ??
143
+ getDemoFromIndexMap(id)
144
+ );
145
+ }
146
+
147
+ async function getDemoFromIndexMap(id: string) {
148
+ const demoIndexMap = await loadDemoIndexMap();
149
+ const demoIndexGetters = Object.values(demoIndexMap).filter(
150
+ (item): item is DemoIndexGetter => Boolean(item),
151
+ );
152
+
153
+ for (const demoIndexGetter of demoIndexGetters) {
154
+ const demo = await getDemoFromDemoIndex(id, demoIndexGetter).catch(
155
+ () => undefined,
156
+ );
157
+ if (demo) return demo;
158
+ }
159
+ }
160
+
70
161
  /**
71
162
  * use demo data by id
72
163
  */
@@ -74,20 +165,30 @@ export function useDemo(
74
165
  id: string,
75
166
  loader?: DemoGetter,
76
167
  version?: string,
168
+ routeId?: string,
77
169
  ): IDemoData | undefined {
78
- const cacheKey = version ? `${id}:${version}` : id;
170
+ const cacheKey = version
171
+ ? `${id}:${version}`
172
+ : routeId
173
+ ? `${id}:route=${routeId}`
174
+ : id;
79
175
  const getter = loader ?? demoIdMap[id];
80
176
 
81
177
  if (!demosCache.get(cacheKey)) {
82
- if (!getter) return undefined;
83
-
84
178
  demosCache.set(
85
179
  cacheKey,
86
- getter().then(({ demos }) => {
87
- // expand context for omit ext
88
- expandDemoContext(demos[id].context);
89
- return demos[id];
90
- }),
180
+ getter
181
+ ? getter().then(({ demos }) => {
182
+ const demo = demos[id];
183
+ if (!demo) return undefined;
184
+
185
+ // expand context for omit ext
186
+ expandDemoContext(demo.context);
187
+ return demo;
188
+ })
189
+ : routeId
190
+ ? getDemoFromRouteIndex(id, routeId)
191
+ : getDemoFromIndexMap(id),
91
192
  );
92
193
 
93
194
  // Reuse local demo data for consumers that still call useDemo(id), such as useLiveDemo.
@@ -101,14 +202,25 @@ export function useDemo(
101
202
  * get all demos
102
203
  */
103
204
  export async function getFullDemos() {
104
- const demoFilesMeta = Object.entries(filesMeta).filter(
105
- ([_id, meta]) => meta.demoIndex,
205
+ const demoIndexMap = await loadDemoIndexMap();
206
+ const lazyDemoIndexes = await Promise.all(
207
+ Object.entries(demoIndexMap).map(async ([id, demoIndexGetter]) => ({
208
+ id,
209
+ demoIndex: await demoIndexGetter?.().catch(() => undefined),
210
+ })),
211
+ );
212
+ const allDemoIndexes = [
213
+ ...demoIndexes,
214
+ ...lazyDemoIndexes,
215
+ ].filter(
216
+ (item): item is { id: string; demoIndex: DemoIndex } =>
217
+ Boolean(item.demoIndex),
106
218
  );
107
219
 
108
220
  return Promise.all(
109
- demoFilesMeta.map(async ([id, meta]) => ({
221
+ allDemoIndexes.map(async ({ id, demoIndex }) => ({
110
222
  id,
111
- demos: (await meta.demoIndex.getter()).demos as Record<string, IDemoData>,
223
+ demos: (await demoIndex.getter()).demos as Record<string, IDemoData>,
112
224
  })),
113
225
  ).then((ret) =>
114
226
  ret.reduce<Record<string, IDemoData>>((total, { id, demos }) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dumi",
3
- "version": "2.4.36",
3
+ "version": "2.4.37",
4
4
  "description": "📖 Documentation Generator of React Component",
5
5
  "keywords": [
6
6
  "generator",