dumi 2.2.6 → 2.3.0-alpha.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.
Files changed (38) hide show
  1. package/dist/client/pages/Demo/index.js +3 -4
  2. package/dist/client/theme-api/DumiDemo/DemoErrorBoundary.d.ts +5 -0
  3. package/dist/client/theme-api/DumiDemo/DemoErrorBoundary.js +16 -0
  4. package/dist/client/theme-api/{DumiDemo.d.ts → DumiDemo/index.d.ts} +1 -1
  5. package/dist/client/theme-api/DumiDemo/index.js +37 -0
  6. package/dist/client/theme-api/DumiDemoGrid.js +4 -1
  7. package/dist/client/theme-api/{context.d.ts → context/index.d.ts} +10 -7
  8. package/dist/client/theme-api/context/index.js +49 -0
  9. package/dist/client/theme-api/context/use.d.ts +7 -0
  10. package/dist/client/theme-api/context/use.js +22 -0
  11. package/dist/client/theme-api/index.d.ts +2 -2
  12. package/dist/client/theme-api/index.js +2 -2
  13. package/dist/client/theme-api/useNavData.js +2 -1
  14. package/dist/client/theme-api/useRouteMeta.js +27 -26
  15. package/dist/client/theme-api/useSidebarData.d.ts +2 -1
  16. package/dist/client/theme-api/useSidebarData.js +1 -1
  17. package/dist/constants.d.ts +1 -0
  18. package/dist/constants.js +4 -0
  19. package/dist/features/compile/index.js +13 -1
  20. package/dist/features/exports.js +2 -1
  21. package/dist/features/meta.js +33 -76
  22. package/dist/features/theme/index.js +19 -55
  23. package/dist/loaders/markdown/index.d.ts +15 -3
  24. package/dist/loaders/markdown/index.js +117 -38
  25. package/dist/templates/ContextWrapper.ts.tpl +89 -0
  26. package/dist/templates/meta-demos.ts.tpl +34 -0
  27. package/dist/templates/meta-frontmatter.ts.tpl +9 -0
  28. package/dist/templates/meta-route.ts.tpl +43 -0
  29. package/dist/templates/meta-runtime.ts.tpl +48 -0
  30. package/dist/templates/meta.ts.tpl +23 -0
  31. package/package.json +2 -1
  32. package/theme-default/builtins/API/index.js +2 -0
  33. package/theme-default/layouts/DocLayout/index.js +1 -1
  34. package/theme-default/slots/ColorSwitch/index.less +5 -4
  35. package/theme-default/slots/ContentTabs/index.js +0 -1
  36. package/theme-default/slots/Toc/index.js +1 -1
  37. package/dist/client/theme-api/DumiDemo.js +0 -46
  38. package/dist/client/theme-api/context.js +0 -16
@@ -1,12 +1,11 @@
1
- import { useParams, useSiteData } from 'dumi';
1
+ import { useDemoData, useParams } from 'dumi';
2
2
  import { createElement } from 'react';
3
3
  import "./index.less";
4
4
  var DemoRenderPage = function DemoRenderPage() {
5
5
  var _useParams = useParams(),
6
6
  id = _useParams.id;
7
- var _useSiteData = useSiteData(),
8
- demos = _useSiteData.demos;
9
- var _ref = demos[id] || {},
7
+ var demoInfo = useDemoData(id);
8
+ var _ref = demoInfo,
10
9
  component = _ref.component;
11
10
  return component && /*#__PURE__*/createElement(component);
12
11
  };
@@ -0,0 +1,5 @@
1
+ import { type FC, type ReactNode } from 'react';
2
+ declare const DemoErrorBoundary: FC<{
3
+ children: ReactNode;
4
+ }>;
5
+ export default DemoErrorBoundary;
@@ -0,0 +1,16 @@
1
+ import Container from 'dumi/theme/builtins/Container';
2
+ import React from 'react';
3
+ import { ErrorBoundary } from 'react-error-boundary';
4
+ var DemoErrorBoundary = function DemoErrorBoundary(props) {
5
+ return /*#__PURE__*/React.createElement(ErrorBoundary, {
6
+ fallbackRender: function fallbackRender(_ref) {
7
+ var error = _ref.error;
8
+ return /*#__PURE__*/React.createElement(Container, {
9
+ type: "error"
10
+ }, /*#__PURE__*/React.createElement("p", null, /*#__PURE__*/React.createElement("strong", null, error.message || 'This demo has been crashed.')), error.stack && /*#__PURE__*/React.createElement("p", null, /*#__PURE__*/React.createElement("details", {
11
+ open: true
12
+ }, /*#__PURE__*/React.createElement("summary", null, "Error stack"), /*#__PURE__*/React.createElement("pre", null, error.stack))));
13
+ }
14
+ }, props.children);
15
+ };
16
+ export default DemoErrorBoundary;
@@ -1,5 +1,5 @@
1
1
  import { type FC } from 'react';
2
- import type { IPreviewerProps } from './types';
2
+ import type { IPreviewerProps } from '../types';
3
3
  export interface IDumiDemoProps {
4
4
  demo: {
5
5
  id: string;
@@ -0,0 +1,37 @@
1
+ function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
2
+ import { SP_ROUTE_PREFIX } from "../../../constants";
3
+ import { useAppData, useDemoData, useSiteData } from 'dumi';
4
+ import React, { createElement } from 'react';
5
+ import Previewer from 'dumi/theme/builtins/Previewer';
6
+ import DemoErrorBoundary from "./DemoErrorBoundary";
7
+ var InternalDumiDemo = function InternalDumiDemo(props) {
8
+ var _useSiteData = useSiteData(),
9
+ historyType = _useSiteData.historyType;
10
+ var _useAppData = useAppData(),
11
+ basename = _useAppData.basename;
12
+ var demoInfo = useDemoData(props.demo.id);
13
+
14
+ // hide debug demo in production
15
+ if (process.env.NODE_ENV === 'production' && props.previewerProps.debug) return null;
16
+ var component = demoInfo.component,
17
+ asset = demoInfo.asset;
18
+ var demoNode = /*#__PURE__*/React.createElement(DemoErrorBoundary, null, /*#__PURE__*/createElement(component));
19
+ if (props.demo.inline) {
20
+ return demoNode;
21
+ }
22
+ var isHashRoute = historyType === 'hash';
23
+ return /*#__PURE__*/React.createElement(Previewer, _extends({
24
+ asset: asset,
25
+ demoUrl:
26
+ // allow user override demoUrl by frontmatter
27
+ props.previewerProps.demoUrl || // when use hash route, browser can automatically handle relative paths starting with #
28
+ "".concat(isHashRoute ? "#" : '').concat(basename).concat(SP_ROUTE_PREFIX, "demos/").concat(props.demo.id)
29
+ }, props.previewerProps), props.previewerProps.iframe ? null : demoNode);
30
+ };
31
+ export var DumiDemo = /*#__PURE__*/React.memo(InternalDumiDemo, function (prev, next) {
32
+ // compare length for performance
33
+ return JSON.stringify(prev).length === JSON.stringify(next).length;
34
+ });
35
+ if (process.env.NODE_ENV !== 'production') {
36
+ InternalDumiDemo.displayName = 'DumiDemo';
37
+ }
@@ -70,4 +70,7 @@ export var DumiDemoGrid = function DumiDemoGrid(props) {
70
70
  }, item));
71
71
  }));
72
72
  }));
73
- };
73
+ };
74
+ if (process.env.NODE_ENV !== 'production') {
75
+ DumiDemoGrid.displayName = 'DumiDemoGrid';
76
+ }
@@ -1,16 +1,17 @@
1
- import type { PICKED_PKG_FIELDS } from "../../constants";
1
+ import type { PICKED_PKG_FIELDS } from "../../../constants";
2
2
  import type { AtomComponentAsset } from 'dumi-assets-types';
3
3
  import { type ComponentType } from 'react';
4
- import type { ILocalesConfig, IPreviewerProps, IThemeConfig } from './types';
4
+ import type { ILocalesConfig, IPreviewerProps, IThemeConfig } from '../types';
5
+ export type DemoInfo = {
6
+ component: ComponentType;
7
+ asset: IPreviewerProps['asset'];
8
+ routeId: string;
9
+ };
5
10
  interface ISiteContext {
6
11
  pkg: Partial<Record<keyof typeof PICKED_PKG_FIELDS, any>>;
7
12
  historyType: 'browser' | 'hash' | 'memory';
8
13
  entryExports: Record<string, any>;
9
- demos: Record<string, {
10
- component: ComponentType;
11
- asset: IPreviewerProps['asset'];
12
- routeId: string;
13
- }>;
14
+ demos: Record<string, DemoInfo>;
14
15
  components: Record<string, AtomComponentAsset>;
15
16
  locales: ILocalesConfig;
16
17
  themeConfig: IThemeConfig;
@@ -21,7 +22,9 @@ interface ISiteContext {
21
22
  * private field, do not use it in your code
22
23
  */
23
24
  _2_level_nav_available: boolean;
25
+ getDemoById: (id: string) => Promise<DemoInfo | null>;
24
26
  }
25
27
  export declare const SiteContext: import("react").Context<ISiteContext>;
26
28
  export declare const useSiteData: () => ISiteContext;
29
+ export declare function useDemoData(demoId: string): DemoInfo | null;
27
30
  export {};
@@ -0,0 +1,49 @@
1
+ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
2
+ function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return exports; }; var exports = {}, Op = Object.prototype, hasOwn = Op.hasOwnProperty, defineProperty = Object.defineProperty || function (obj, key, desc) { obj[key] = desc.value; }, $Symbol = "function" == typeof Symbol ? Symbol : {}, iteratorSymbol = $Symbol.iterator || "@@iterator", asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator", toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: !0, configurable: !0, writable: !0 }), obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator, generator = Object.create(protoGenerator.prototype), context = new Context(tryLocsList || []); return defineProperty(generator, "_invoke", { value: makeInvokeMethod(innerFn, self, context) }), generator; } function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } exports.wrap = wrap; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; define(IteratorPrototype, iteratorSymbol, function () { return this; }); var getProto = Object.getPrototypeOf, NativeIteratorPrototype = getProto && getProto(getProto(values([]))); NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype); var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if ("throw" !== record.type) { var result = record.arg, value = result.value; return value && "object" == _typeof(value) && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }) : PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped, resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } reject(record.arg); } var previousPromise; defineProperty(this, "_invoke", { value: function value(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(innerFn, self, context) { var state = "suspendedStart"; return function (method, arg) { if ("executing" === state) throw new Error("Generator is already running"); if ("completed" === state) { if ("throw" === method) throw arg; return doneResult(); } for (context.method = method, context.arg = arg;;) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) { if ("suspendedStart" === state) throw state = "completed", context.arg; context.dispatchException(context.arg); } else "return" === context.method && context.abrupt("return", context.arg); state = "executing"; var record = tryCatch(innerFn, self, context); if ("normal" === record.type) { if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue; return { value: record.arg, done: context.done }; } "throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg); } }; } function maybeInvokeDelegate(delegate, context) { var methodName = context.method, method = delegate.iterator[methodName]; if (undefined === method) return context.delegate = null, "throw" === methodName && delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method) || "return" !== methodName && (context.method = "throw", context.arg = new TypeError("The iterator does not provide a '" + methodName + "' method")), ContinueSentinel; var record = tryCatch(method, delegate.iterator, context.arg); if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel; var info = record.arg; return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel); } function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal", delete record.arg, entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0); } function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) return iteratorMethod.call(iterable); if ("function" == typeof iterable.next) return iterable; if (!isNaN(iterable.length)) { var i = -1, next = function next() { for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next; return next.value = undefined, next.done = !0, next; }; return next.next = next; } } return { next: doneResult }; } function doneResult() { return { value: undefined, done: !0 }; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), defineProperty(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) { var ctor = "function" == typeof genFun && genFun.constructor; return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name)); }, exports.mark = function (genFun) { return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun; }, exports.awrap = function (arg) { return { __await: arg }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () { return this; }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { void 0 === PromiseImpl && (PromiseImpl = Promise); var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () { return this; }), define(Gp, "toString", function () { return "[object Generator]"; }), exports.keys = function (val) { var object = Object(val), keys = []; for (var key in object) keys.push(key); return keys.reverse(), function next() { for (; keys.length;) { var key = keys.pop(); if (key in object) return next.value = key, next.done = !1, next; } return next.done = !0, next; }; }, exports.values = values, Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined); }, stop: function stop() { this.done = !0; var rootRecord = this.tryEntries[0].completion; if ("throw" === rootRecord.type) throw rootRecord.arg; return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) throw exception; var context = this; function handle(loc, caught) { return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i], record = entry.completion; if ("root" === entry.tryLoc) return handle("end"); if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"), hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } else if (hasCatch) { if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0); } else { if (!hasFinally) throw new Error("try statement without catch or finally"); if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null); var record = finallyEntry ? finallyEntry.completion : {}; return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record); }, complete: function complete(record, afterLoc) { if ("throw" === record.type) throw record.arg; return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel; } }, catch: function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if ("throw" === record.type) { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { return this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }, "next" === this.method && (this.arg = undefined), ContinueSentinel; } }, exports; }
3
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
4
+ function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
5
+ import { createContext, useContext } from 'react';
6
+ import use from "./use";
7
+ export var SiteContext = /*#__PURE__*/createContext({
8
+ pkg: {},
9
+ historyType: 'browser',
10
+ entryExports: {},
11
+ demos: {},
12
+ components: {},
13
+ locales: [],
14
+ themeConfig: {},
15
+ loading: false,
16
+ setLoading: function setLoading() {},
17
+ _2_level_nav_available: true,
18
+ getDemoById: function () {
19
+ var _getDemoById = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee() {
20
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
21
+ while (1) switch (_context.prev = _context.next) {
22
+ case 0:
23
+ return _context.abrupt("return", null);
24
+ case 1:
25
+ case "end":
26
+ return _context.stop();
27
+ }
28
+ }, _callee);
29
+ }));
30
+ function getDemoById() {
31
+ return _getDemoById.apply(this, arguments);
32
+ }
33
+ return getDemoById;
34
+ }()
35
+ });
36
+ export var useSiteData = function useSiteData() {
37
+ return useContext(SiteContext);
38
+ };
39
+ var cache = new Map();
40
+
41
+ // Async load demo data
42
+ export function useDemoData(demoId) {
43
+ var _useSiteData = useSiteData(),
44
+ getDemoById = _useSiteData.getDemoById;
45
+ if (!cache.has(demoId)) {
46
+ cache.set(demoId, getDemoById(demoId));
47
+ }
48
+ return use(cache.get(demoId));
49
+ }
@@ -0,0 +1,7 @@
1
+ type ReactPromise<T> = Promise<T> & {
2
+ status?: 'pending' | 'fulfilled' | 'rejected';
3
+ value?: T;
4
+ reason?: any;
5
+ };
6
+ export default function use<T>(promise: ReactPromise<T>): T;
7
+ export {};
@@ -0,0 +1,22 @@
1
+ // Copy from React official demo.
2
+ // This will be replace if React release new version of use hooks
3
+
4
+ export default function use(promise) {
5
+ if (promise.status === 'fulfilled') {
6
+ return promise.value;
7
+ } else if (promise.status === 'rejected') {
8
+ throw promise.reason;
9
+ } else if (promise.status === 'pending') {
10
+ throw promise;
11
+ } else {
12
+ promise.status = 'pending';
13
+ promise.then(function (result) {
14
+ promise.status = 'fulfilled';
15
+ promise.value = result;
16
+ }, function (reason) {
17
+ promise.status = 'rejected';
18
+ promise.reason = reason;
19
+ });
20
+ throw promise;
21
+ }
22
+ }
@@ -1,9 +1,9 @@
1
- export { createIntlCache, defineMessages, FormattedDate, FormattedDateParts, FormattedDisplayName, FormattedList, FormattedMessage, FormattedNumber, FormattedNumberParts, FormattedPlural, FormattedRelativeTime, FormattedTime, FormattedTimeParts, injectIntl, IntlContext, IntlProvider, RawIntlProvider, useIntl, } from 'react-intl';
1
+ export { FormattedDate, FormattedDateParts, FormattedDisplayName, FormattedList, FormattedMessage, FormattedNumber, FormattedNumberParts, FormattedPlural, FormattedRelativeTime, FormattedTime, FormattedTimeParts, IntlContext, IntlProvider, RawIntlProvider, createIntlCache, defineMessages, injectIntl, useIntl, } from 'react-intl';
2
2
  export { AtomRenderer } from './AtomRenderer';
3
- export { useSiteData } from './context';
4
3
  export { DumiDemo } from './DumiDemo';
5
4
  export { DumiDemoGrid } from './DumiDemoGrid';
6
5
  export { DumiPage } from './DumiPage';
6
+ export { useDemoData, useSiteData } from './context';
7
7
  export { openCodeSandbox } from './openCodeSandbox';
8
8
  export { openStackBlitz } from './openStackBlitz';
9
9
  export type { IPreviewerProps } from './types';
@@ -1,9 +1,9 @@
1
- export { createIntlCache, defineMessages, FormattedDate, FormattedDateParts, FormattedDisplayName, FormattedList, FormattedMessage, FormattedNumber, FormattedNumberParts, FormattedPlural, FormattedRelativeTime, FormattedTime, FormattedTimeParts, injectIntl, IntlContext, IntlProvider, RawIntlProvider, useIntl } from 'react-intl';
1
+ export { FormattedDate, FormattedDateParts, FormattedDisplayName, FormattedList, FormattedMessage, FormattedNumber, FormattedNumberParts, FormattedPlural, FormattedRelativeTime, FormattedTime, FormattedTimeParts, IntlContext, IntlProvider, RawIntlProvider, createIntlCache, defineMessages, injectIntl, useIntl } from 'react-intl';
2
2
  export { AtomRenderer } from "./AtomRenderer";
3
- export { useSiteData } from "./context";
4
3
  export { DumiDemo } from "./DumiDemo";
5
4
  export { DumiDemoGrid } from "./DumiDemoGrid";
6
5
  export { DumiPage } from "./DumiPage";
6
+ export { useDemoData, useSiteData } from "./context";
7
7
  export { openCodeSandbox } from "./openCodeSandbox";
8
8
  export { openStackBlitz } from "./openStackBlitz";
9
9
  export { useAtomAssets } from "./useAtomAssets";
@@ -16,6 +16,7 @@ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _ty
16
16
  function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
17
17
  import { useFullSidebarData, useLocale, useSiteData } from 'dumi';
18
18
  import { useState } from 'react';
19
+ import { getLocaleClearPath } from "./useSidebarData";
19
20
  import { getLocaleNav, pickRouteSortMeta, useLocaleDocRoutes, useRouteDataComparer } from "./utils";
20
21
  function genNavItem(meta, groups, activePath, link) {
21
22
  return _objectSpread({
@@ -69,7 +70,7 @@ export var useNavData = function useNavData() {
69
70
  var _ref6 = _slicedToArray(_ref5, 2),
70
71
  link = _ref6[0],
71
72
  groups = _ref6[1];
72
- var _ref7 = link.match(/^(\/[^/]+)([^]+)?$/),
73
+ var _ref7 = "/".concat(getLocaleClearPath(link.replace(/^\//, ''), locale)).match(/^(\/[^/]+)([^]+)?$/),
73
74
  _ref8 = _slicedToArray(_ref7, 3),
74
75
  parentPath = _ref8[1],
75
76
  restPath = _ref8[2];
@@ -1,12 +1,19 @@
1
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
2
- function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
3
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
4
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
5
- function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
6
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
7
- import { matchRoutes, useAppData, useLocation, useRouteData } from 'dumi';
8
- import { useCallback, useState } from 'react';
9
- import { useIsomorphicLayoutEffect } from "./utils";
1
+ function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
2
+ import { getRouteMetaById, matchRoutes, useAppData, useLocation, useRouteData } from 'dumi';
3
+ import { useMemo } from 'react';
4
+ import use from "./context/use";
5
+ var cache = new Map();
6
+ var useAsyncRouteMeta = function useAsyncRouteMeta(id) {
7
+ if (!cache.has(id)) {
8
+ cache.set(id, getRouteMetaById(id));
9
+ }
10
+ return use(cache.get(id));
11
+ };
12
+ var emptyMeta = {
13
+ frontmatter: {},
14
+ toc: [],
15
+ texts: []
16
+ };
10
17
 
11
18
  /**
12
19
  * hook for get matched route meta
@@ -18,29 +25,23 @@ export var useRouteMeta = function useRouteMeta() {
18
25
  pathname = _useLocation.pathname;
19
26
  var _useAppData = useAppData(),
20
27
  clientRoutes = _useAppData.clientRoutes;
21
- var getter = useCallback(function () {
22
- var ret;
28
+ var curRoute = useMemo(function () {
23
29
  if (route.path === pathname && !('isLayout' in route)) {
24
30
  // use `useRouteData` result if matched, for performance
25
- ret = route.meta;
31
+ return route;
26
32
  } else {
27
- var _matchRoutes, _matched$route;
33
+ var _matchRoutes;
28
34
  // match manually for dynamic route & layout component
29
35
  var matched = (_matchRoutes = matchRoutes(clientRoutes, pathname)) === null || _matchRoutes === void 0 ? void 0 : _matchRoutes.pop();
30
- ret = matched === null || matched === void 0 ? void 0 : (_matched$route = matched.route) === null || _matched$route === void 0 ? void 0 : _matched$route.meta;
36
+ return matched === null || matched === void 0 ? void 0 : matched.route;
31
37
  }
32
- return ret || {
33
- frontmatter: {},
34
- toc: [],
35
- texts: []
36
- };
37
- }, [clientRoutes.length, pathname]);
38
- var _useState = useState(getter),
39
- _useState2 = _slicedToArray(_useState, 2),
40
- meta = _useState2[0],
41
- setMeta = _useState2[1];
42
- useIsomorphicLayoutEffect(function () {
43
- setMeta(getter);
44
38
  }, [clientRoutes.length, pathname]);
39
+ var meta = useAsyncRouteMeta(curRoute === null || curRoute === void 0 ? void 0 : curRoute.id) || emptyMeta;
40
+ if (curRoute && 'meta' in curRoute && _typeof(curRoute.meta) === 'object') {
41
+ Object.keys(curRoute.meta).forEach(function (key) {
42
+ var _ref, _ref$key;
43
+ (_ref$key = (_ref = meta)[key]) !== null && _ref$key !== void 0 ? _ref$key : _ref[key] = curRoute.meta[key];
44
+ });
45
+ }
45
46
  return meta;
46
47
  };
@@ -1,4 +1,5 @@
1
- import type { ISidebarGroup } from './types';
1
+ import type { ILocalesConfig, ISidebarGroup } from './types';
2
+ export declare const getLocaleClearPath: (routePath: string, locale: ILocalesConfig[0]) => string;
2
3
  /**
3
4
  * hook for get sidebar data for all nav
4
5
  */
@@ -19,7 +19,7 @@ import { useLocale, useLocation, useRouteMeta, useSiteData } from 'dumi';
19
19
  import { useState } from 'react';
20
20
  import { pickRouteSortMeta, useLocaleDocRoutes, useRouteDataComparer } from "./utils";
21
21
  var DEFAULT_GROUP_STUB_TITLE = '$default-group-title';
22
- var getLocaleClearPath = function getLocaleClearPath(routePath, locale) {
22
+ export var getLocaleClearPath = function getLocaleClearPath(routePath, locale) {
23
23
  return 'base' in locale ? routePath.replace(locale.base.slice(1), '').replace(/^\//, '') : routePath;
24
24
  };
25
25
 
@@ -17,3 +17,4 @@ export declare const PICKED_PKG_FIELDS: {
17
17
  export declare const USELESS_TMP_FILES: string[];
18
18
  export declare const VERSION_2_LEVEL_NAV = "^2.2.0";
19
19
  export declare const VERSION_2_DEPRECATE_SOFT_BREAKS = "^2.2.0";
20
+ export declare const TEMPLATES_DIR: string;
package/dist/constants.js CHANGED
@@ -26,12 +26,14 @@ __export(constants_exports, {
26
26
  PREFERS_COLOR_ATTR: () => PREFERS_COLOR_ATTR,
27
27
  PREFERS_COLOR_LS_KEY: () => PREFERS_COLOR_LS_KEY,
28
28
  SP_ROUTE_PREFIX: () => SP_ROUTE_PREFIX,
29
+ TEMPLATES_DIR: () => TEMPLATES_DIR,
29
30
  THEME_PREFIX: () => THEME_PREFIX,
30
31
  USELESS_TMP_FILES: () => USELESS_TMP_FILES,
31
32
  VERSION_2_DEPRECATE_SOFT_BREAKS: () => VERSION_2_DEPRECATE_SOFT_BREAKS,
32
33
  VERSION_2_LEVEL_NAV: () => VERSION_2_LEVEL_NAV
33
34
  });
34
35
  module.exports = __toCommonJS(constants_exports);
36
+ var import_path = require("path");
35
37
  var LOCAL_DUMI_DIR = ".dumi";
36
38
  var LOCAL_THEME_DIR = `${LOCAL_DUMI_DIR}/theme`;
37
39
  var LOCAL_PAGES_DIR = `${LOCAL_DUMI_DIR}/pages`;
@@ -51,6 +53,7 @@ var PICKED_PKG_FIELDS = {
51
53
  var USELESS_TMP_FILES = ["tsconfig.json", "typings.d.ts"];
52
54
  var VERSION_2_LEVEL_NAV = "^2.2.0";
53
55
  var VERSION_2_DEPRECATE_SOFT_BREAKS = "^2.2.0";
56
+ var TEMPLATES_DIR = (0, import_path.join)(__dirname, "./templates");
54
57
  // Annotate the CommonJS export names for ESM import in node:
55
58
  0 && (module.exports = {
56
59
  LOCAL_DUMI_DIR,
@@ -60,6 +63,7 @@ var VERSION_2_DEPRECATE_SOFT_BREAKS = "^2.2.0";
60
63
  PREFERS_COLOR_ATTR,
61
64
  PREFERS_COLOR_LS_KEY,
62
65
  SP_ROUTE_PREFIX,
66
+ TEMPLATES_DIR,
63
67
  THEME_PREFIX,
64
68
  USELESS_TMP_FILES,
65
69
  VERSION_2_DEPRECATE_SOFT_BREAKS,
@@ -83,11 +83,23 @@ var compile_default = (api) => {
83
83
  (0, import_assets.addExampleAssets)(assets);
84
84
  },
85
85
  onResolveAtomMeta: import_assets.addAtomMeta
86
+ }).end().end().oneOf("md-demo").resourceQuery(/demo$/).use("babel-loader").loader(babelInUmi.loader).options(babelInUmi.options).end().use("md-demo-loader").loader(loaderPath).options({
87
+ ...loaderBaseOpts,
88
+ mode: "demo"
89
+ }).end().end().oneOf("md-demo-index").resourceQuery(/demo-index$/).use("md-demo-index-loader").loader(loaderPath).options({
90
+ ...loaderBaseOpts,
91
+ mode: "demo-index"
92
+ }).end().end().oneOf("md-frontmatter").resourceQuery(/frontmatter$/).use("md-frontmatter-loader").loader(loaderPath).options({
93
+ ...loaderBaseOpts,
94
+ mode: "frontmatter"
95
+ }).end().end().oneOf("md-text").resourceQuery(/text$/).use("md-text-loader").loader(loaderPath).options({
96
+ ...loaderBaseOpts,
97
+ mode: "text"
86
98
  }).end().end().oneOf("md").use("babel-loader").loader(babelInUmi.loader).options(babelInUmi.options).end().use("md-loader").loader(loaderPath).options({
87
99
  ...loaderBaseOpts,
88
100
  builtins: api.service.themeData.builtins
89
101
  });
90
- memo.module.rule("dumi-page").type("javascript/auto").test(/\.(j|t)sx?$/).resourceQuery(/meta$/).use("page-meta-loader").loader(require.resolve("../../loaders/page"));
102
+ memo.module.rule("dumi-page").type("javascript/auto").test(/\.(j|t)sx?$/).resourceQuery(/(meta|frontmatter)$/).use("page-meta-loader").loader(require.resolve("../../loaders/page"));
91
103
  memo.module.rule("dumi-demo").type("javascript/auto").test(/\..+$/).enforce("pre").resourceQuery(/techStack/).use("demo-loader").loader(require.resolve("../../loaders/demo")).options({ techStacks, cwd: api.cwd });
92
104
  memo.module.rule("dumi-raw").type("javascript/auto").post().resourceQuery(/dumi-raw/).use("raw-loader").loader(require.resolve("raw-loader")).end().use("pre-raw-loader").loader(require.resolve("../../loaders/pre-raw"));
93
105
  if (api.env === "development" && memo.plugins.has("fastRefresh")) {
@@ -44,7 +44,8 @@ var exports_default = (api) => {
44
44
  noPluginDir: true,
45
45
  path: "dumi/exports.ts",
46
46
  content: `export * from '../exports';
47
- export * from '${(0, import_plugin_utils.winPath)(require.resolve("../client/theme-api"))}';`
47
+ export * from '${(0, import_plugin_utils.winPath)(require.resolve("../client/theme-api"))}';
48
+ export { getRouteMetaById } from './meta/route-meta';`
48
49
  });
49
50
  });
50
51
  };
@@ -34,6 +34,7 @@ __export(meta_exports, {
34
34
  default: () => meta_default
35
35
  });
36
36
  module.exports = __toCommonJS(meta_exports);
37
+ var import_constants = require("../constants");
37
38
  var import_path = __toESM(require("path"));
38
39
  var import_plugin_utils = require("umi/plugin-utils");
39
40
  var import_tabs = require("./tabs");
@@ -65,89 +66,45 @@ var meta_default = (api) => {
65
66
  path: ATOMS_META_PATH,
66
67
  content: "export const components = null;"
67
68
  });
69
+ const parsedMetaFiles = await api.applyPlugins({
70
+ type: api.ApplyPluginsType.modify,
71
+ key: "dumi.modifyMetaFiles",
72
+ initialValue: JSON.parse(JSON.stringify(metaFiles))
73
+ });
68
74
  api.writeTmpFile({
69
75
  noPluginDir: true,
70
- path: "dumi/meta/index.ts",
71
- content: import_plugin_utils.Mustache.render(
72
- `{{#metaFiles}}
73
- import { demos as dm{{{index}}}, frontmatter as fm{{{index}}}, toc as toc{{{index}}}, texts as txt{{{index}}} } from '{{{file}}}?type=meta';
74
- {{/metaFiles}}
75
-
76
- export { components } from './atoms';
77
- export { tabs } from './tabs';
78
-
79
- export const filesMeta = {
80
- {{#metaFiles}}
81
- '{{{id}}}': {
82
- frontmatter: fm{{{index}}},
83
- toc: toc{{{index}}},
84
- texts: txt{{{index}}},
85
- demos: dm{{{index}}},
86
- {{#tabs}}
87
- tabs: {{{tabs}}},
88
- {{/tabs}}
89
- },
90
- {{/metaFiles}}
91
- }
92
-
93
- // generate demos data in runtime, for reuse route.id to reduce bundle size
94
- export const demos = Object.entries(filesMeta).reduce((acc, [id, meta]) => {
95
- // append route id to demo
96
- Object.values(meta.demos).forEach((demo) => {
97
- demo.routeId = id;
98
- });
99
- // merge demos
100
- Object.assign(acc, meta.demos);
101
-
102
- // remove demos from meta, to avoid deep clone demos in umi routes/children compatible logic
103
- delete meta.demos;
104
-
105
- return acc;
106
- }, {});
107
- `,
108
- {
109
- metaFiles: await api.applyPlugins({
110
- type: api.ApplyPluginsType.modify,
111
- key: "dumi.modifyMetaFiles",
112
- initialValue: metaFiles
113
- })
114
- }
115
- )
76
+ path: "dumi/meta/frontmatter.ts",
77
+ tplPath: (0, import_plugin_utils.winPath)((0, import_path.join)(import_constants.TEMPLATES_DIR, "meta-frontmatter.ts.tpl")),
78
+ context: {
79
+ metaFiles: parsedMetaFiles
80
+ }
81
+ });
82
+ const mdFiles = parsedMetaFiles.filter(
83
+ (metaFile) => metaFile.file.endsWith(".md")
84
+ );
85
+ api.writeTmpFile({
86
+ noPluginDir: true,
87
+ path: "dumi/meta/demos.ts",
88
+ tplPath: (0, import_plugin_utils.winPath)((0, import_path.join)(import_constants.TEMPLATES_DIR, "meta-demos.ts.tpl")),
89
+ context: {
90
+ metaFiles: mdFiles
91
+ }
92
+ });
93
+ api.writeTmpFile({
94
+ noPluginDir: true,
95
+ path: "dumi/meta/route-meta.ts",
96
+ tplPath: (0, import_plugin_utils.winPath)((0, import_path.join)(import_constants.TEMPLATES_DIR, "meta-route.ts.tpl")),
97
+ context: {
98
+ metaFiles: mdFiles
99
+ }
116
100
  });
117
101
  api.writeTmpFile({
118
102
  noPluginDir: true,
119
103
  path: "dumi/meta/runtime.ts",
120
- content: `import { filesMeta, tabs } from '.';
121
- import deepmerge from '${(0, import_plugin_utils.winPath)(
122
- import_path.default.dirname(require.resolve("deepmerge/package"))
123
- )}';
124
- export const patchRoutes = ({ routes }) => {
125
- Object.values(routes).forEach((route) => {
126
- if (filesMeta[route.id]) {
127
- if (process.env.NODE_ENV === 'production' && (route.meta?.frontmatter?.debug || filesMeta[route.id].frontmatter.debug)) {
128
- // hide route in production which set hide frontmatter
129
- delete routes[route.id];
130
- } else {
131
- // merge meta to route object
132
- route.meta = deepmerge(route.meta, filesMeta[route.id]);
133
-
134
- // apply real tab data from id
135
- route.meta.tabs = route.meta.tabs?.map((id) => {
136
- const meta = {
137
- frontmatter: { title: tabs[id].title },
138
- toc: [],
139
- texts: [],
140
- }
141
- return {
142
- ...tabs[id],
143
- meta: filesMeta[id] || meta,
144
- }
145
- });
104
+ tplPath: (0, import_plugin_utils.winPath)((0, import_path.join)(import_constants.TEMPLATES_DIR, "meta-runtime.ts.tpl")),
105
+ context: {
106
+ deepmerge: (0, import_plugin_utils.winPath)(import_path.default.dirname(require.resolve("deepmerge/package")))
146
107
  }
147
- }
148
- });
149
- }
150
- `
151
108
  });
152
109
  });
153
110
  api.addRuntimePlugin(() => "@@/dumi/meta/runtime.ts");