dumi 2.3.0-beta.3 → 2.3.0-beta.4

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 (41) hide show
  1. package/dist/client/misc/reactDemoCompiler.d.ts +3 -0
  2. package/dist/client/misc/reactDemoCompiler.js +24 -0
  3. package/dist/client/pages/Demo/index.js +15 -0
  4. package/dist/client/theme-api/types.d.ts +9 -0
  5. package/dist/client/theme-api/useLiveDemo.d.ts +7 -3
  6. package/dist/client/theme-api/useLiveDemo.js +133 -50
  7. package/dist/client/theme-api/useNavData.js +11 -8
  8. package/dist/client/theme-api/usePrefersColor.js +1 -1
  9. package/dist/client/theme-api/useRouteMeta.d.ts +1 -1
  10. package/dist/client/theme-api/useRouteMeta.js +4 -8
  11. package/dist/client/theme-api/useSidebarData.d.ts +9 -1
  12. package/dist/client/theme-api/useSidebarData.js +9 -6
  13. package/dist/client/theme-api/useSiteSearch/useSearchData.js +2 -1
  14. package/dist/client/theme-api/utils.d.ts +0 -10
  15. package/dist/client/theme-api/utils.js +0 -25
  16. package/dist/constants.d.ts +1 -0
  17. package/dist/constants.js +3 -0
  18. package/dist/features/compile/index.js +39 -10
  19. package/dist/features/exports.js +0 -2
  20. package/dist/features/parser.js +23 -1
  21. package/dist/features/theme/index.js +13 -11
  22. package/dist/loaders/markdown/index.js +20 -3
  23. package/dist/loaders/markdown/transformer/index.d.ts +2 -1
  24. package/dist/loaders/markdown/transformer/rehypeDemo.js +5 -2
  25. package/dist/loaders/markdown/transformer/remarkEmbed.js +2 -1
  26. package/dist/techStacks/react.d.ts +1 -0
  27. package/dist/techStacks/react.js +3 -0
  28. package/dist/templates/meta/exports.ts.tpl +33 -1
  29. package/dist/types.d.ts +14 -0
  30. package/dist/utils.d.ts +1 -3
  31. package/dist/utils.js +8 -2
  32. package/package.json +1 -1
  33. package/theme-default/builtins/Previewer/index.js +11 -32
  34. package/theme-default/builtins/Previewer/index.less +43 -11
  35. package/theme-default/slots/ColorSwitch/index.js +4 -1
  36. package/theme-default/slots/PreviewerActions/index.d.ts +1 -0
  37. package/theme-default/slots/PreviewerActions/index.js +18 -20
  38. package/theme-default/slots/SearchBar/index.less +3 -0
  39. package/theme-default/slots/SearchResult/index.js +18 -5
  40. package/theme-default/slots/SourceCodeEditor/index.d.ts +1 -0
  41. package/theme-default/slots/SourceCodeEditor/index.js +8 -31
@@ -0,0 +1,3 @@
1
+ import type { IDemoCompileFn } from '../theme-api/types';
2
+ declare const compile: IDemoCompileFn;
3
+ export default compile;
@@ -0,0 +1,24 @@
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 { transform } from 'sucrase';
6
+ var compile = /*#__PURE__*/function () {
7
+ var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(code) {
8
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
9
+ while (1) switch (_context.prev = _context.next) {
10
+ case 0:
11
+ return _context.abrupt("return", transform(code, {
12
+ transforms: ['typescript', 'jsx', 'imports']
13
+ }).code);
14
+ case 1:
15
+ case "end":
16
+ return _context.stop();
17
+ }
18
+ }, _callee);
19
+ }));
20
+ return function compile(_x) {
21
+ return _ref.apply(this, arguments);
22
+ };
23
+ }();
24
+ export default compile;
@@ -8,8 +8,11 @@ var DemoRenderPage = function DemoRenderPage() {
8
8
  component = _ref.component;
9
9
  var _useLiveDemo = useLiveDemo(id),
10
10
  liveDemoNode = _useLiveDemo.node,
11
+ liveDemoError = _useLiveDemo.error,
11
12
  setSource = _useLiveDemo.setSource;
12
13
  var finalNode = liveDemoNode || component && /*#__PURE__*/createElement(component);
14
+
15
+ // listen message event for setSource
13
16
  useEffect(function () {
14
17
  var handler = function handler(ev) {
15
18
  if (ev.data.type === 'dumi.liveDemo.setSource') {
@@ -21,6 +24,18 @@ var DemoRenderPage = function DemoRenderPage() {
21
24
  return window.removeEventListener('message', handler);
22
25
  };
23
26
  }, [setSource]);
27
+
28
+ // notify parent window that compile done
29
+ useEffect(function () {
30
+ if (liveDemoNode || liveDemoError) {
31
+ window.postMessage({
32
+ type: 'dumi.liveDemo.compileDone',
33
+ value: {
34
+ err: liveDemoError
35
+ }
36
+ });
37
+ }
38
+ }, [liveDemoNode, liveDemoError]);
24
39
  return finalNode;
25
40
  };
26
41
  export default DemoRenderPage;
@@ -219,10 +219,19 @@ export type IRoutesById = Record<string, {
219
219
  redirect?: string;
220
220
  [key: string]: any;
221
221
  }>;
222
+ export type IDemoCompileFn = (code: string, opts: {
223
+ filename: string;
224
+ }) => Promise<string>;
222
225
  export type IDemoData = {
223
226
  component: ComponentType;
224
227
  asset: IPreviewerProps['asset'];
225
228
  routeId: string;
226
229
  context?: Record<string, unknown>;
230
+ renderOpts?: {
231
+ /**
232
+ * provide a runtime compile function for compile demo code for live preview
233
+ */
234
+ compile?: IDemoCompileFn;
235
+ };
227
236
  };
228
237
  export {};
@@ -1,6 +1,10 @@
1
- import { type ReactNode } from 'react';
2
- export declare const useLiveDemo: (id: string) => {
1
+ import { type ReactNode, type RefObject } from 'react';
2
+ export declare const useLiveDemo: (id: string, opts?: {
3
+ containerRef?: RefObject<HTMLElement>;
4
+ iframe?: boolean;
5
+ }) => {
3
6
  node: ReactNode;
7
+ loading: boolean;
4
8
  error: Error | null;
5
- setSource: (source: Record<string, string>) => void;
9
+ setSource: (source: Record<string, string>) => Promise<void>;
6
10
  };
@@ -1,3 +1,7 @@
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); }); }; }
1
5
  function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
2
6
  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
7
  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); }
@@ -5,65 +9,144 @@ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len
5
9
  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
10
  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
7
11
  import { useDemo } from 'dumi';
8
- import { createElement, useCallback, useState } from 'react';
12
+ import throttle from 'lodash.throttle';
13
+ import { createElement, useCallback, useRef, useState } from 'react';
9
14
  import DemoErrorBoundary from "./DumiDemo/DemoErrorBoundary";
10
- export var useLiveDemo = function useLiveDemo(id) {
15
+ var THROTTLE_WAIT = 500;
16
+ export var useLiveDemo = function useLiveDemo(id, opts) {
11
17
  var _ref = useDemo(id),
12
18
  context = _ref.context,
13
- asset = _ref.asset;
14
- var _useState = useState(),
19
+ asset = _ref.asset,
20
+ renderOpts = _ref.renderOpts;
21
+ var _useState = useState(false),
15
22
  _useState2 = _slicedToArray(_useState, 2),
16
- demoNode = _useState2[0],
17
- setDemoNode = _useState2[1];
18
- var _useState3 = useState(null),
23
+ loading = _useState2[0],
24
+ setLoading = _useState2[1];
25
+ var loadingTimer = useRef();
26
+ var taskToken = useRef();
27
+ var _useState3 = useState(),
19
28
  _useState4 = _slicedToArray(_useState3, 2),
20
- error = _useState4[0],
21
- setError = _useState4[1];
22
- var setSource = useCallback(function (source) {
23
- var entryFileName = Object.keys(asset.dependencies).find(function (k) {
24
- return asset.dependencies[k].type === 'FILE';
25
- });
26
- var entryFileCode = source[entryFileName];
27
- var require = function require(v) {
28
- if (v in context) return context[v];
29
- throw new Error("Cannot find module: ".concat(v));
30
- };
31
- var exports = {};
32
- var module = {
33
- exports: exports
34
- };
35
-
36
- // lazy load react-dom/server
37
- import('react-dom/server').then(function (_ref2) {
38
- var renderToStaticMarkup = _ref2.renderToStaticMarkup;
39
- try {
40
- // initial component with fake runtime
41
- new Function('module', 'exports', 'require', entryFileCode)(module, exports, require);
42
- var newDemoNode = /*#__PURE__*/createElement(DemoErrorBoundary, null, /*#__PURE__*/createElement(exports.default));
43
- var oError = console.error;
29
+ demoNode = _useState4[0],
30
+ setDemoNode = _useState4[1];
31
+ var _useState5 = useState(null),
32
+ _useState6 = _slicedToArray(_useState5, 2),
33
+ error = _useState6[0],
34
+ setError = _useState6[1];
35
+ var setSource = useCallback(throttle( /*#__PURE__*/function () {
36
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(source) {
37
+ var _opts$containerRef;
38
+ var iframeWindow, entryFileName, require, exports, module, token, entryFileCode, renderToStaticMarkupDeferred, newDemoNode, oError;
39
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
40
+ while (1) switch (_context.prev = _context.next) {
41
+ case 0:
42
+ // set loading status if still compiling after 499ms
43
+ loadingTimer.current = window.setTimeout(function () {
44
+ setLoading(true);
45
+ },
46
+ // make sure timer be fired before next throttle
47
+ THROTTLE_WAIT - 1);
48
+ if (!(opts !== null && opts !== void 0 && opts.iframe && opts !== null && opts !== void 0 && (_opts$containerRef = opts.containerRef) !== null && _opts$containerRef !== void 0 && _opts$containerRef.current)) {
49
+ _context.next = 7;
50
+ break;
51
+ }
52
+ iframeWindow = opts.containerRef.current.querySelector('iframe').contentWindow;
53
+ _context.next = 5;
54
+ return new Promise(function (resolve) {
55
+ var handler = function handler(ev) {
56
+ if (ev.data.type.startsWith('dumi.liveDemo.compileDone')) {
57
+ iframeWindow.removeEventListener('message', handler);
58
+ setError(ev.data.value.err);
59
+ resolve();
60
+ }
61
+ };
62
+ iframeWindow.addEventListener('message', handler);
63
+ iframeWindow.postMessage({
64
+ type: 'dumi.liveDemo.setSource',
65
+ value: source
66
+ });
67
+ });
68
+ case 5:
69
+ _context.next = 36;
70
+ break;
71
+ case 7:
72
+ entryFileName = Object.keys(asset.dependencies).find(function (k) {
73
+ return asset.dependencies[k].type === 'FILE';
74
+ });
75
+ require = function require(v) {
76
+ if (v in context) return context[v];
77
+ throw new Error("Cannot find module: ".concat(v));
78
+ };
79
+ exports = {};
80
+ module = {
81
+ exports: exports
82
+ };
83
+ token = taskToken.current = Math.random();
84
+ entryFileCode = source[entryFileName];
85
+ _context.prev = 13;
86
+ // load renderToStaticMarkup in async way
87
+ renderToStaticMarkupDeferred = import('react-dom/server').then(function (_ref3) {
88
+ var renderToStaticMarkup = _ref3.renderToStaticMarkup;
89
+ return renderToStaticMarkup;
90
+ }); // compile entry file code
91
+ _context.next = 17;
92
+ return renderOpts.compile(entryFileCode, {
93
+ filename: entryFileName
94
+ });
95
+ case 17:
96
+ entryFileCode = _context.sent;
97
+ if (!(token !== taskToken.current)) {
98
+ _context.next = 20;
99
+ break;
100
+ }
101
+ return _context.abrupt("return");
102
+ case 20:
103
+ // initial component with fake runtime
104
+ new Function('module', 'exports', 'require', entryFileCode)(module, exports, require);
105
+ newDemoNode = /*#__PURE__*/createElement(DemoErrorBoundary, null, /*#__PURE__*/createElement(exports.default));
106
+ oError = console.error; // hijack console.error to avoid useLayoutEffect error
107
+ console.error = function () {
108
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
109
+ args[_key] = arguments[_key];
110
+ }
111
+ return !args[0].includes('useLayoutEffect does nothing on the server') && oError.apply(console, args);
112
+ };
44
113
 
45
- // hijack console.error to avoid useLayoutEffect error
46
- console.error = function () {
47
- for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
48
- args[_key] = arguments[_key];
49
- }
50
- return !args[0].includes('useLayoutEffect does nothing on the server') && oError.apply(console, args);
51
- };
114
+ // check component is able to render, to avoid show react overlay error
115
+ _context.next = 26;
116
+ return renderToStaticMarkupDeferred;
117
+ case 26:
118
+ _context.t0 = _context.sent;
119
+ (0, _context.t0)(newDemoNode);
120
+ console.error = oError;
52
121
 
53
- // check component is renderable, to avoid show react overlay error
54
- renderToStaticMarkup(newDemoNode);
55
- console.error = oError;
56
-
57
- // set new demo node with passing source
58
- setDemoNode(newDemoNode);
59
- setError(null);
60
- } catch (err) {
61
- setError(err);
62
- }
63
- });
64
- }, [context]);
122
+ // set new demo node with passing source
123
+ setDemoNode(newDemoNode);
124
+ setError(null);
125
+ _context.next = 36;
126
+ break;
127
+ case 33:
128
+ _context.prev = 33;
129
+ _context.t1 = _context["catch"](13);
130
+ setError(_context.t1);
131
+ case 36:
132
+ // reset loading status
133
+ clearTimeout(loadingTimer.current);
134
+ setLoading(false);
135
+ case 38:
136
+ case "end":
137
+ return _context.stop();
138
+ }
139
+ }, _callee, null, [[13, 33]]);
140
+ }));
141
+ return function (_x2) {
142
+ return _ref2.apply(this, arguments);
143
+ };
144
+ }(), THROTTLE_WAIT, {
145
+ leading: true
146
+ }), [context, asset, renderOpts]);
65
147
  return {
66
148
  node: demoNode,
149
+ loading: loading,
67
150
  error: error,
68
151
  setSource: setSource
69
152
  };
@@ -16,7 +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
+ import { getLocaleClearPath, getRouteParentPath } from "./useSidebarData";
20
20
  import { getLocaleNav, pickRouteSortMeta, useLocaleDocRoutes, useRouteDataComparer } from "./utils";
21
21
  function genNavItem(meta, groups, activePath, link) {
22
22
  return _objectSpread({
@@ -70,11 +70,14 @@ export var useNavData = function useNavData() {
70
70
  var _ref6 = _slicedToArray(_ref5, 2),
71
71
  link = _ref6[0],
72
72
  groups = _ref6[1];
73
- var _ref7 = "/".concat(getLocaleClearPath(link.replace(/^\//, ''), locale)).match(/^(\/[^/]+)([^]+)?$/),
74
- _ref8 = _slicedToArray(_ref7, 3),
75
- parentPath = _ref8[1],
76
- restPath = _ref8[2];
77
- var isNestedNav = Boolean(restPath) && is2LevelNav;
73
+ var clearPath = getLocaleClearPath(link.replace(/^\//, ''), locale);
74
+ var parentPath = link.replace(clearPath, function (s) {
75
+ return getRouteParentPath(s, {
76
+ is2LevelNav: is2LevelNav,
77
+ locale: locale
78
+ });
79
+ });
80
+ var isNestedNav = link.length > parentPath.length && is2LevelNav;
78
81
  var _Object$values$reduce = Object.values(routes).reduce(function (ret, route) {
79
82
  // find routes which within the nav path
80
83
  if (route.path.startsWith(link.slice(1))) {
@@ -90,14 +93,14 @@ export var useNavData = function useNavData() {
90
93
  if (isNestedNav) {
91
94
  var _firstMeta$title, _ret$parentPath, _second$children;
92
95
  // fallback to use parent path as 1-level nav title
93
- (_firstMeta$title = firstMeta.title) !== null && _firstMeta$title !== void 0 ? _firstMeta$title : firstMeta.title = parentPath.slice(1).replace(/^[a-z]/, function (s) {
96
+ (_firstMeta$title = firstMeta.title) !== null && _firstMeta$title !== void 0 ? _firstMeta$title : firstMeta.title = parentPath.split('/').pop().replace(/^[a-z]/, function (s) {
94
97
  return s.toUpperCase();
95
98
  });
96
99
 
97
100
  // handle nested nav item as parent children
98
101
  var second = (_ret$parentPath = ret[parentPath]) !== null && _ret$parentPath !== void 0 ? _ret$parentPath : ret[parentPath] = genNavItem(firstMeta, groups, parentPath);
99
102
  (_second$children = second.children) !== null && _second$children !== void 0 ? _second$children : second.children = [];
100
- ret[parentPath].children.push(genNavItem(secondMeta, groups, link, groups[0].children[0].link));
103
+ second.children.push(genNavItem(secondMeta, groups, link, groups[0].children[0].link));
101
104
  } else {
102
105
  // handle root nav item
103
106
  ret[link] = genNavItem(firstMeta, groups, link, groups[0].children[0].link);
@@ -126,7 +126,7 @@ var ColorChanger = /*#__PURE__*/function () {
126
126
  }
127
127
  this.prefersColor = color;
128
128
  this.color = color === 'auto' ? this.isColorMode('dark') ? 'dark' : 'light' : color;
129
- document.documentElement.setAttribute(PREFERS_COLOR_ATTR, color);
129
+ document.documentElement.setAttribute(PREFERS_COLOR_ATTR, this.color);
130
130
  this.applyCallbacks();
131
131
  return color;
132
132
  }
@@ -2,4 +2,4 @@ import type { IRouteMeta } from './types';
2
2
  /**
3
3
  * hook for get matched route meta
4
4
  */
5
- export declare const useRouteMeta: () => IRouteMeta;
5
+ export declare const useRouteMeta: () => IRouteMeta | Promise<IRouteMeta>;
@@ -6,7 +6,7 @@ function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefine
6
6
  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
7
7
  import { getRouteMetaById, matchRoutes, useAppData, useLocation, useRouteData } from 'dumi';
8
8
  import { useCallback, useState } from 'react';
9
- import { use, useIsomorphicLayoutEffect } from "./utils";
9
+ import { useIsomorphicLayoutEffect } from "./utils";
10
10
  var cache = new Map();
11
11
  var EMPTY_META = {
12
12
  frontmatter: {},
@@ -32,13 +32,12 @@ function getCachedRouteMeta(route) {
32
32
  var meta = merge(getRouteMetaById(route.id, {
33
33
  syncOnly: true
34
34
  }));
35
- var ret = Promise.resolve(meta);
36
35
  var proxyGetter = function proxyGetter(target, prop) {
37
36
  if (ASYNC_META_PROPS.includes(prop)) {
38
37
  if (!cache.get(pendingCacheKey)) {
39
38
  // load async meta then replace cache
40
39
  cache.set(pendingCacheKey, getRouteMetaById(route.id).then(function (full) {
41
- return cache.set(cacheKey, Promise.resolve(merge(full))).get(cacheKey);
40
+ return cache.set(cacheKey, merge(full)).get(cacheKey);
42
41
  }));
43
42
  }
44
43
 
@@ -48,16 +47,13 @@ function getCachedRouteMeta(route) {
48
47
  return target[prop];
49
48
  };
50
49
 
51
- // return sync meta by default
52
- ret.status = 'fulfilled';
53
-
54
50
  // load async meta if property accessed
55
51
  (_meta$tabs = meta.tabs) === null || _meta$tabs === void 0 ? void 0 : _meta$tabs.forEach(function (tab) {
56
52
  tab.meta = new Proxy(tab.meta, {
57
53
  get: proxyGetter
58
54
  });
59
55
  });
60
- ret.value = new Proxy(meta, {
56
+ var ret = new Proxy(meta, {
61
57
  get: proxyGetter
62
58
  });
63
59
  cache.set(cacheKey, ret);
@@ -92,7 +88,7 @@ export var useRouteMeta = function useRouteMeta() {
92
88
  _useState2 = _slicedToArray(_useState, 2),
93
89
  matchedRoute = _useState2[0],
94
90
  setMatchedRoute = _useState2[1];
95
- var meta = use(getCachedRouteMeta(matchedRoute));
91
+ var meta = getCachedRouteMeta(matchedRoute);
96
92
  useIsomorphicLayoutEffect(function () {
97
93
  setMatchedRoute(getter);
98
94
  }, [clientRoutes.length, pathname]);
@@ -1,5 +1,13 @@
1
- import type { ILocalesConfig, ISidebarGroup } from './types';
1
+ import type { ILocalesConfig, IRouteMeta, ISidebarGroup } from './types';
2
2
  export declare const getLocaleClearPath: (routePath: string, locale: ILocalesConfig[0]) => string;
3
+ /**
4
+ * get parent path from route path
5
+ */
6
+ export declare function getRouteParentPath(path: string, { meta, is2LevelNav, locale, }: {
7
+ meta?: IRouteMeta;
8
+ is2LevelNav: boolean;
9
+ locale: ILocalesConfig[0];
10
+ }): string;
3
11
  /**
4
12
  * hook for get sidebar data for all nav
5
13
  */
@@ -26,11 +26,12 @@ export var getLocaleClearPath = function getLocaleClearPath(routePath, locale) {
26
26
  /**
27
27
  * get parent path from route path
28
28
  */
29
- function getRouteParentPath(path, _ref) {
30
- var _meta$frontmatter$fil;
29
+ export function getRouteParentPath(path, _ref) {
31
30
  var meta = _ref.meta,
32
- is2LevelNav = _ref.is2LevelNav;
33
- var isIndexDocRoute = ((_meta$frontmatter$fil = meta.frontmatter.filename) === null || _meta$frontmatter$fil === void 0 ? void 0 : _meta$frontmatter$fil.endsWith('index.md')) && !meta._atom_route && is2LevelNav;
31
+ is2LevelNav = _ref.is2LevelNav,
32
+ locale = _ref.locale;
33
+ var indexDocRegex = new RegExp("/index(\\.".concat(locale.id, ")?.md$"));
34
+ var isIndexDocRoute = (meta === null || meta === void 0 ? void 0 : meta.frontmatter.filename) && indexDocRegex.test(meta.frontmatter.filename) && !meta._atom_route && is2LevelNav;
34
35
  var paths = path.split('/')
35
36
  // strip end slash
36
37
  .filter(Boolean);
@@ -74,7 +75,8 @@ export var useFullSidebarData = function useFullSidebarData() {
74
75
  var parentPath = "/".concat(route.path.replace(clearPath, function (s) {
75
76
  return getRouteParentPath(s, {
76
77
  is2LevelNav: is2LevelNav,
77
- meta: route.meta
78
+ meta: route.meta,
79
+ locale: locale
78
80
  });
79
81
  }));
80
82
  var _pickRouteSortMeta = pickRouteSortMeta({
@@ -227,7 +229,8 @@ export var useSidebarData = function useSidebarData() {
227
229
  var parentPath = clearPath ? pathname.replace(clearPath, function (s) {
228
230
  return getRouteParentPath(s, {
229
231
  is2LevelNav: is2LevelNav,
230
- meta: meta
232
+ meta: meta,
233
+ locale: locale
231
234
  });
232
235
  }) : pathname;
233
236
  return parentPath ? sidebar[parentPath] : [];
@@ -1,5 +1,5 @@
1
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
- var _excluded = ["component", "context"];
2
+ var _excluded = ["renderOpts", "component", "context"];
3
3
  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; }
4
4
  function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
5
5
  function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
@@ -55,6 +55,7 @@ export default function useSearchData() {
55
55
  var _ref3 = _slicedToArray(_ref2, 2),
56
56
  id = _ref3[0],
57
57
  _ref3$ = _ref3[1],
58
+ renderOpts = _ref3$.renderOpts,
58
59
  component = _ref3$.component,
59
60
  context = _ref3$.context,
60
61
  demo = _objectWithoutProperties(_ref3$, _excluded);
@@ -28,13 +28,3 @@ export declare const useRouteDataComparer: <T extends {
28
28
  */
29
29
  export declare const pickRouteSortMeta: (original: Partial<Pick<INavItem, 'order' | 'title'>>, field: 'nav' | 'nav.second' | 'group', fm: IRouteMeta['frontmatter']) => Partial<Pick<INavItem, "title" | "order">>;
30
30
  export declare function getLocaleNav(nav: IUserNavValue | INav, locale: ILocale): import("./types").IUserNavItems;
31
- type ReactPromise<T> = Promise<T> & {
32
- status?: 'pending' | 'fulfilled' | 'rejected';
33
- value?: T;
34
- reason?: any;
35
- };
36
- /**
37
- * @private Internal usage. Safe to remove
38
- */
39
- export declare function use<T>(promise: ReactPromise<T>): T;
40
- export {};
@@ -96,29 +96,4 @@ export var pickRouteSortMeta = function pickRouteSortMeta(original, field, fm) {
96
96
  };
97
97
  export function getLocaleNav(nav, locale) {
98
98
  return Array.isArray(nav) ? nav : nav[locale.id];
99
- }
100
-
101
- // Copy from React official demo.
102
-
103
- /**
104
- * @private Internal usage. Safe to remove
105
- */
106
- export function use(promise) {
107
- if (promise.status === 'fulfilled') {
108
- return promise.value;
109
- } else if (promise.status === 'rejected') {
110
- throw promise.reason;
111
- } else if (promise.status === 'pending') {
112
- throw promise;
113
- } else {
114
- promise.status = 'pending';
115
- promise.then(function (result) {
116
- promise.status = 'fulfilled';
117
- promise.value = result;
118
- }, function (reason) {
119
- promise.status = 'rejected';
120
- promise.reason = reason;
121
- });
122
- throw promise;
123
- }
124
99
  }
@@ -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 FS_CACHE_DIR = "node_modules/.cache/dumi";