@antv/dumi-theme-antv 0.3.8 → 0.3.11

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 (31) hide show
  1. package/dist/pages/404.js +2 -2
  2. package/dist/pages/Example/index.js +7 -7
  3. package/dist/plugin/index.js +26 -12
  4. package/dist/plugin/rehypeObservable.d.ts +1 -0
  5. package/dist/plugin/{utils.js → rehypeObservable.js} +43 -22
  6. package/dist/slots/CodeEditor/Toolbar.d.ts +1 -0
  7. package/dist/slots/CodeEditor/Toolbar.js +6 -5
  8. package/dist/slots/CodeEditor/index.js +220 -54
  9. package/dist/slots/CodeEditor/utils.d.ts +1 -1
  10. package/dist/slots/CodeEditor/utils.js +2 -1
  11. package/dist/slots/Header/Search/SearchResult.d.ts +21 -0
  12. package/dist/slots/Header/Search/SearchResult.js +35 -0
  13. package/dist/slots/Header/Search/SearchResult.module.less +65 -0
  14. package/dist/slots/Header/Search/helper.d.ts +8 -0
  15. package/dist/slots/Header/Search/helper.js +25 -0
  16. package/dist/slots/Header/Search/index.d.ts +2 -0
  17. package/dist/slots/Header/Search/index.js +59 -0
  18. package/dist/slots/Header/{Search.module.less → Search/index.module.less} +1 -9
  19. package/dist/slots/ManualContent/Preview.d.ts +7 -0
  20. package/dist/slots/ManualContent/Preview.js +203 -0
  21. package/dist/slots/ManualContent/Preview.module.less +62 -0
  22. package/dist/slots/ManualContent/index.js +11 -9
  23. package/dist/slots/ManualContent/usePreview.d.ts +1 -0
  24. package/dist/slots/ManualContent/usePreview.js +97 -0
  25. package/dist/slots/ManualContent/utils.d.ts +1 -0
  26. package/dist/slots/ManualContent/utils.js +7 -4
  27. package/dist/slots/utils.js +16 -5
  28. package/package.json +7 -3
  29. package/dist/plugin/utils.d.ts +0 -5
  30. package/dist/slots/Header/Search.d.ts +0 -12
  31. package/dist/slots/Header/Search.js +0 -87
package/dist/pages/404.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import React from 'react';
2
- import { SEO } from "dumi/theme/slots/SEO";
3
- import { Header } from "dumi/theme/slots/Header";
4
2
  import { NotFound as NotFoundPage } from "dumi/theme/slots/404";
5
3
  import { Footer } from "dumi/theme/slots/Footer";
4
+ import { Header } from "dumi/theme/slots/Header";
5
+ import { SEO } from "dumi/theme/slots/SEO";
6
6
 
7
7
  /**
8
8
  * 404 页面
@@ -4,17 +4,17 @@ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o =
4
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
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
6
  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
7
- import React, { useContext, useEffect, useState } from 'react';
8
- import { useParams, useLocation, useNavigate } from 'react-router-dom';
9
- import { get } from 'lodash-es';
10
7
  import { Layout } from 'antd';
11
8
  import { useLocale, useSiteData } from 'dumi';
12
- import { SEO } from "dumi/theme/slots/SEO";
13
- import { Header } from "dumi/theme/slots/Header";
14
- import { ExampleSider } from "dumi/theme/slots/ExampleSider";
9
+ import { get } from 'lodash-es';
10
+ import React, { useContext, useEffect, useState } from 'react';
11
+ import { useLocation, useNavigate, useParams } from 'react-router-dom';
12
+ import { ThemeAntVContext } from "../../context";
15
13
  import { CodeRunner } from "dumi/theme/slots/CodeRunner";
16
14
  import { getDemoInfo } from "../../slots/CodeRunner/utils";
17
- import { ThemeAntVContext } from "../../context";
15
+ import { ExampleSider } from "dumi/theme/slots/ExampleSider";
16
+ import { Header } from "dumi/theme/slots/Header";
17
+ import { SEO } from "dumi/theme/slots/SEO";
18
18
  import styles from "./index.module.less";
19
19
  import { getCurrentTitle } from "./utils";
20
20
  var Sider = Layout.Sider,
@@ -32,9 +32,12 @@ __export(plugin_exports, {
32
32
  default: () => plugin_default
33
33
  });
34
34
  module.exports = __toCommonJS(plugin_exports);
35
+ var import_plugin_utils = require("dumi/plugin-utils");
35
36
  var path = __toESM(require("path"));
36
37
  var import_examples = require("./examples");
37
- var import_utils = require("./utils");
38
+ var import_rehypeObservable = __toESM(require("./rehypeObservable"));
39
+ var ALIAS_PAGES_KEY = "@/antv__theme__pages";
40
+ var MOCK_META = { frontmatter: { title: "mock-meta" }, texts: [], toc: [] };
38
41
  var plugin_default = (api) => {
39
42
  api.describe({ key: `dumi-theme:${require("../../package.json").name}` });
40
43
  api.modifyDefaultConfig((memo) => {
@@ -42,7 +45,11 @@ var plugin_default = (api) => {
42
45
  memo.exportStatic.extraRoutePaths = (0, import_examples.getExamplePaths)();
43
46
  memo.mfsu = false;
44
47
  memo.jsMinifier = "terser";
45
- memo.favicons = ["https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*7svFR6wkPMoAAAAAAAAAAAAADmJ7AQ/original"];
48
+ memo.favicons = [
49
+ "https://mdn.alipayobjects.com/huamei_qa8qxu/afts/img/A*7svFR6wkPMoAAAAAAAAAAAAADmJ7AQ/original"
50
+ ];
51
+ memo.alias[ALIAS_PAGES_KEY] = path.join(__dirname, "../pages");
52
+ memo.extraRehypePlugins = [import_rehypeObservable.default];
46
53
  return memo;
47
54
  });
48
55
  const pages = [
@@ -62,26 +69,25 @@ var plugin_default = (api) => {
62
69
  {
63
70
  id: "dumi-theme-antv-example-list-zh",
64
71
  absPath: "/examples",
65
- file: (0, import_utils.myResolve)("../pages/Examples/index.tsx")
72
+ file: `${ALIAS_PAGES_KEY}/Examples`
66
73
  },
67
74
  {
68
75
  id: "dumi-theme-antv-example-list-lang",
69
76
  absPath: "/:language/examples",
70
- file: (0, import_utils.myResolve)("../pages/Examples/index.tsx")
77
+ file: `${ALIAS_PAGES_KEY}/Examples`
71
78
  },
72
79
  // single example preview page.
73
80
  {
74
81
  id: "dumi-theme-antv-single-example-zh",
75
82
  absPath: "/examples/:topic/:example",
76
- file: (0, import_utils.myResolve)("../pages/Example/index.tsx")
83
+ file: `${ALIAS_PAGES_KEY}/Example`
77
84
  },
78
85
  {
79
86
  id: "dumi-theme-antv-single-example-lang",
80
87
  absPath: "/:language/examples/:topic/:example",
81
- file: (0, import_utils.myResolve)("../pages/Example/index.tsx")
88
+ file: `${ALIAS_PAGES_KEY}/Example`
82
89
  }
83
90
  ];
84
- const contextFilePath = (0, import_utils.myResolve)("../context.ts");
85
91
  api.onGenerateFiles(() => {
86
92
  api.writeTmpFile({
87
93
  noPluginDir: true,
@@ -89,7 +95,9 @@ var plugin_default = (api) => {
89
95
  content: `
90
96
  import React from 'react';
91
97
  import { useOutlet, useSiteData } from 'dumi';
92
- import { ThemeAntVContext } from '${contextFilePath}';
98
+ import { ThemeAntVContext } from '${(0, import_plugin_utils.winPath)(
99
+ path.join(__dirname, "../context")
100
+ )}';
93
101
 
94
102
  export default function ThemeAntVContextWrapper() {
95
103
  const outlet = useOutlet();
@@ -98,7 +106,9 @@ export default function ThemeAntVContextWrapper() {
98
106
  <ThemeAntVContext.Provider
99
107
  value={{
100
108
  meta: ${JSON.stringify({
101
- exampleTopics: (0, import_examples.getExamplesPageTopics)(api.config.themeConfig.examples || [])
109
+ exampleTopics: (0, import_examples.getExamplesPageTopics)(
110
+ api.config.themeConfig.examples || []
111
+ )
102
112
  })}
103
113
  }}
104
114
  >
@@ -120,13 +130,17 @@ export default function ThemeAntVContextWrapper() {
120
130
  path: page.absPath.slice(1),
121
131
  absPath: page.absPath,
122
132
  file: page.file,
123
- parentId: "DocLayout"
133
+ parentId: "DocLayout",
134
+ meta: MOCK_META
124
135
  };
125
136
  });
126
- routes["404"].file = (0, import_utils.myResolve)("../pages/404.tsx");
137
+ routes["404"].file = `${ALIAS_PAGES_KEY}/404`;
138
+ routes["404"].meta = MOCK_META;
127
139
  return routes;
128
140
  });
129
- api.addTmpGenerateWatcherPaths(() => [path.resolve(process.cwd(), "examples")]);
141
+ api.addTmpGenerateWatcherPaths(() => [
142
+ path.resolve(process.cwd(), "examples")
143
+ ]);
130
144
  };
131
145
  // Annotate the CommonJS export names for ESM import in node:
132
146
  0 && (module.exports = {});
@@ -0,0 +1 @@
1
+ export default function rehypeObservable(): (tree: any) => Promise<void>;
@@ -26,28 +26,49 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
26
26
  ));
27
27
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
28
 
29
- // src/plugin/utils.ts
30
- var utils_exports = {};
31
- __export(utils_exports, {
32
- myResolve: () => myResolve
29
+ // src/plugin/rehypeObservable.ts
30
+ var rehypeObservable_exports = {};
31
+ __export(rehypeObservable_exports, {
32
+ default: () => rehypeObservable
33
33
  });
34
- module.exports = __toCommonJS(utils_exports);
35
- var path = __toESM(require("path"));
36
- function myResolve(p, alternateExts = [".js"]) {
37
- const extname2 = path.extname(p);
38
- const pathname = p.slice(0, p.length - extname2.length);
39
- const exts = [extname2, ...alternateExts];
40
- for (let i = 0; i < exts.length; i++) {
41
- const ext = exts[i];
42
- const fullpath = `${pathname}${ext}`;
43
- try {
44
- return require.resolve(fullpath);
45
- } catch (e) {
46
- }
47
- }
48
- return "";
34
+ module.exports = __toCommonJS(rehypeObservable_exports);
35
+ var visit;
36
+ (async () => {
37
+ ({ visit } = await import("unist-util-visit"));
38
+ })();
39
+ function isObservable(node) {
40
+ if (!node.data)
41
+ return;
42
+ const { meta } = node.data;
43
+ if (!meta)
44
+ return;
45
+ return meta.match(/\|\s*ob\s*{*/);
46
+ }
47
+ function rehypeObservable() {
48
+ return async (tree) => {
49
+ visit(tree, "element", (node, i, parent) => {
50
+ if (!isObservable(node))
51
+ return;
52
+ if (node.tagName === "SourceCode") {
53
+ parent.children.splice(i, 1, {
54
+ type: "element",
55
+ tagName: "div",
56
+ properties: {
57
+ class: "ob-codeblock"
58
+ },
59
+ children: [
60
+ {
61
+ type: "element",
62
+ tagName: "p",
63
+ properties: { meta: node.data.meta },
64
+ children: []
65
+ },
66
+ { ...node }
67
+ ]
68
+ });
69
+ }
70
+ });
71
+ };
49
72
  }
50
73
  // Annotate the CommonJS export names for ESM import in node:
51
- 0 && (module.exports = {
52
- myResolve
53
- });
74
+ 0 && (module.exports = {});
@@ -1,6 +1,7 @@
1
1
  import React from 'react';
2
2
  export declare enum EDITOR_TABS {
3
3
  JAVASCRIPT = "JavaScript",
4
+ SPEC = "Spec",
4
5
  DATA = "Data"
5
6
  }
6
7
  declare type ToolbarProps = {
@@ -10,19 +10,20 @@ function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key i
10
10
  function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
11
11
  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); }
12
12
  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); }
13
- import React, { useEffect, useState } from 'react';
14
13
  import { CodeSandboxOutlined, PlayCircleOutlined, ThunderboltOutlined } from '@ant-design/icons';
15
- import { Typography, Tooltip } from 'antd';
16
- import { useLocale, FormattedMessage } from 'dumi';
17
- import { getParameters } from 'codesandbox/lib/api/define';
18
14
  import stackblitzSdk from '@stackblitz/sdk';
15
+ import { Tooltip, Typography } from 'antd';
16
+ import { getParameters } from 'codesandbox/lib/api/define';
17
+ import { FormattedMessage, useLocale } from 'dumi';
18
+ import React, { useEffect, useState } from 'react';
19
19
  import { ping } from "../utils";
20
- import { extractImportDeps, getCodeSandboxConfig, getStackblitzConfig, getRiddleConfig } from "./utils";
20
+ import { extractImportDeps, getCodeSandboxConfig, getRiddleConfig, getStackblitzConfig } from "./utils";
21
21
  import styles from "./Toolbar.module.less";
22
22
  var Paragraph = Typography.Paragraph;
23
23
  export var EDITOR_TABS;
24
24
  (function (EDITOR_TABS) {
25
25
  EDITOR_TABS["JAVASCRIPT"] = "JavaScript";
26
+ EDITOR_TABS["SPEC"] = "Spec";
26
27
  EDITOR_TABS["DATA"] = "Data";
27
28
  })(EDITOR_TABS || (EDITOR_TABS = {}));
28
29
  export var Toolbar = function Toolbar(_ref) {
@@ -1,18 +1,29 @@
1
+ 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; }
2
+ 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); } }
3
+ 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); }); }; }
4
+ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
5
+ function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
6
+ function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
7
+ function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
8
+ 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); }
1
9
  function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
2
10
  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
11
  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
12
  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
13
  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
14
  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
7
- import React, { useRef, useState, useCallback, useEffect } from 'react';
8
15
  import MonacoEditor, { loader } from '@monaco-editor/react';
9
- import { useSiteData, useLocale } from 'dumi';
16
+ import { autoType as d3AutoType, dsvFormat } from 'd3-dsv';
17
+ import { useLocale, useSiteData } from 'dumi';
10
18
  import { debounce, noop } from 'lodash-es';
19
+ import { format } from 'prettier';
20
+ import parserBabel from 'prettier/parser-babel';
21
+ import React, { useCallback, useEffect, useRef, useState } from 'react';
11
22
  import { bind, clear } from 'size-sensor';
12
- import { replaceInsertCss, execute, compile } from "./utils";
13
- import { Toolbar, EDITOR_TABS } from "./Toolbar";
14
23
  import { Loading } from "dumi/theme/slots/Loading";
24
+ import { EDITOR_TABS, Toolbar } from "./Toolbar";
15
25
  import styles from "./index.module.less";
26
+ import { compile, execute, replaceInsertCss } from "./utils";
16
27
  loader.config({
17
28
  'vs/nls': {
18
29
  availableLanguages: {
@@ -46,31 +57,41 @@ export var CodeEditor = function CodeEditor(_ref) {
46
57
  _ref$onFullscreen = _ref.onFullscreen,
47
58
  onFullscreen = _ref$onFullscreen === void 0 ? noop : _ref$onFullscreen;
48
59
  var locale = useLocale();
49
- var _useSiteData$themeCon = useSiteData().themeConfig.playground.extraLib,
50
- extraLib = _useSiteData$themeCon === void 0 ? '' : _useSiteData$themeCon;
60
+ var _useSiteData = useSiteData(),
61
+ themeConfig = _useSiteData.themeConfig;
62
+ var _themeConfig$es = themeConfig.es5,
63
+ es5 = _themeConfig$es === void 0 ? true : _themeConfig$es,
64
+ _themeConfig$showSpec = themeConfig.showSpecTab,
65
+ showSpecTab = _themeConfig$showSpec === void 0 ? false : _themeConfig$showSpec;
66
+ var _themeConfig$playgrou = themeConfig.playground.extraLib,
67
+ extraLib = _themeConfig$playgrou === void 0 ? '' : _themeConfig$playgrou;
51
68
  // 编辑器两个 tab,分别是代码和数据
52
69
  var _useState = useState(null),
53
70
  _useState2 = _slicedToArray(_useState, 2),
54
71
  data = _useState2[0],
55
72
  setData = _useState2[1];
56
- var _useState3 = useState(source),
73
+ var _useState3 = useState(null),
57
74
  _useState4 = _slicedToArray(_useState3, 2),
58
- code = _useState4[0],
59
- setCode = _useState4[1];
75
+ spec = _useState4[0],
76
+ setSpec = _useState4[1];
77
+ var _useState5 = useState(source),
78
+ _useState6 = _slicedToArray(_useState5, 2),
79
+ code = _useState6[0],
80
+ setCode = _useState6[1];
60
81
  // monaco instance
61
82
  var monacoRef = useRef(null);
62
83
  // 文件后缀
63
84
  var fileExtension = relativePath.split('.')[relativePath.split('.').length - 1] || 'js';
64
85
  // 菜单栏
65
- var _useState5 = useState([]),
66
- _useState6 = _slicedToArray(_useState5, 2),
67
- editorTabs = _useState6[0],
68
- setEditorTabs = _useState6[1];
69
- // 当前选中菜单栏
70
- var _useState7 = useState(EDITOR_TABS.JAVASCRIPT),
86
+ var _useState7 = useState([]),
71
87
  _useState8 = _slicedToArray(_useState7, 2),
72
- currentEditorTab = _useState8[0],
73
- setCurrentEditorTab = _useState8[1];
88
+ editorTabs = _useState8[0],
89
+ setEditorTabs = _useState8[1];
90
+ // 当前选中菜单栏
91
+ var _useState9 = useState(EDITOR_TABS.JAVASCRIPT),
92
+ _useState10 = _slicedToArray(_useState9, 2),
93
+ currentEditorTab = _useState10[0],
94
+ setCurrentEditorTab = _useState10[1];
74
95
  var containerId = "playgroundScriptContainer_".concat(exampleId);
75
96
 
76
97
  // 出发 auto resize
@@ -112,7 +133,7 @@ export var CodeEditor = function CodeEditor(_ref) {
112
133
  // 1. 先编译代码
113
134
  var compiled;
114
135
  try {
115
- compiled = compile(replaceInsertCss(v, locale.id), relativePath);
136
+ compiled = compile(replaceInsertCss(v, locale.id), relativePath, es5);
116
137
  } catch (e) {
117
138
  reportError(e);
118
139
  // 执行出错,后面的步骤不用做了!
@@ -122,10 +143,39 @@ export var CodeEditor = function CodeEditor(_ref) {
122
143
  // 2. 执行代码,try catch 在内部已经做了
123
144
  execute(compiled, containerId, playground === null || playground === void 0 ? void 0 : playground.container, replaceId);
124
145
  }, 300), [exampleId, currentEditorTab]);
146
+ var updateData = function updateData(data) {
147
+ if (!data) return;
148
+ var tabs = showSpecTab ? [EDITOR_TABS.JAVASCRIPT, EDITOR_TABS.SPEC, EDITOR_TABS.DATA] : [EDITOR_TABS.JAVASCRIPT, EDITOR_TABS.DATA];
149
+ setEditorTabs(tabs);
150
+ setData(data);
151
+ };
152
+
153
+ // 找到 spec 里面的 online data 并且更新它
154
+ var updateDataFromSpec = function updateDataFromSpec(options) {
155
+ if (!options) return;
156
+ var discoverd = [options];
157
+ var dataList = [];
158
+ while (discoverd.length) {
159
+ var node = discoverd.pop();
160
+ var _data = node.data;
161
+ if (_typeof(_data) === 'object' && _data.type === 'fetch') {
162
+ dataList.push(_data);
163
+ }
164
+ discoverd.push.apply(discoverd, _toConsumableArray(node.children || []));
165
+ }
166
+ fetchData(dataList.map(function (d) {
167
+ return d.value;
168
+ })).then(updateData);
169
+ };
125
170
 
126
- // 案例变化的时候,修改期待吗
171
+ // 案例变化的时候,修改代码
127
172
  useEffect(function () {
128
173
  setCode(source);
174
+
175
+ // 清空 data 和 spec
176
+ // 放在该案例运行错误,返回之前案例的 data 和 spec
177
+ setData(null);
178
+ if (showSpecTab) setSpec(null);
129
179
  }, [exampleId]);
130
180
 
131
181
  // 代码变化的时候,运行代码
@@ -158,21 +208,88 @@ export var CodeEditor = function CodeEditor(_ref) {
158
208
  };
159
209
  }, []);
160
210
 
211
+ // fetch 多份远程数据,如果有多份合并成一份。
212
+ var fetchData = /*#__PURE__*/function () {
213
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(urls) {
214
+ var parseCSV, parseJSON, dataList;
215
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
216
+ while (1) switch (_context.prev = _context.next) {
217
+ case 0:
218
+ parseCSV = function parseCSV(response) {
219
+ return response.text().then(function (text) {
220
+ return dsvFormat(',').parse(text, d3AutoType);
221
+ });
222
+ };
223
+ parseJSON = function parseJSON(response) {
224
+ return response.json();
225
+ };
226
+ _context.next = 4;
227
+ return Promise.all(urls.map(function (url) {
228
+ return fetch(url).then(function (response) {
229
+ var format = url.split('.').pop();
230
+ if (format === 'csv') return parseCSV(response);
231
+ return parseJSON(response);
232
+ });
233
+ }));
234
+ case 4:
235
+ dataList = _context.sent;
236
+ if (!(dataList.length <= 1)) {
237
+ _context.next = 7;
238
+ break;
239
+ }
240
+ return _context.abrupt("return", dataList[0]);
241
+ case 7:
242
+ return _context.abrupt("return", Object.fromEntries(urls.map(function (url, index) {
243
+ return [url, dataList[index]];
244
+ })));
245
+ case 8:
246
+ case "end":
247
+ return _context.stop();
248
+ }
249
+ }, _callee);
250
+ }));
251
+ return function fetchData(_x2) {
252
+ return _ref2.apply(this, arguments);
253
+ };
254
+ }();
255
+
256
+ // 切换 example 的时候,切换到代码编辑页面
257
+ // 用于更新当前 example 的 spec 和 data
258
+ useEffect(function () {
259
+ setCurrentEditorTab(EDITOR_TABS.JAVASCRIPT);
260
+ }, [exampleId]);
261
+
161
262
  // hook 用户的数据
162
263
  useEffect(function () {
163
- var dataFileMatch = source.match(/fetch\('(.*)'\)/);
264
+ // 需要匹配首位的换行符,以及 ' 和 "
265
+ var match = source.matchAll(/fetch\(\s*["|'](.*)["|'],*\s*\)/g);
266
+ var dataFileMatch = Array.from(match);
164
267
  if (dataFileMatch && dataFileMatch.length > 0) {
165
- fetch(dataFileMatch[1]).then(function (response) {
166
- return response.json();
167
- }).then(function (data) {
168
- setEditorTabs([EDITOR_TABS.JAVASCRIPT, EDITOR_TABS.DATA]);
169
- setData(data);
268
+ fetchData(dataFileMatch.map(function (d) {
269
+ return d[1].trim();
270
+ })).then(function (data) {
271
+ updateData(data);
170
272
  });
171
273
  } else {
172
- setEditorTabs([EDITOR_TABS.JAVASCRIPT]);
274
+ var tabs = showSpecTab ? [EDITOR_TABS.JAVASCRIPT, EDITOR_TABS.SPEC] : [EDITOR_TABS.JAVASCRIPT];
275
+ setEditorTabs(tabs);
173
276
  }
174
277
  }, [exampleId]);
175
278
 
279
+ // 监听更新 spec 的事件,这是一个定义事件,需要在 .dumi/global.ts 里面 dispatch
280
+ useEffect(function () {
281
+ var update = function update(e) {
282
+ var _ref3 = e.detail,
283
+ options = _ref3.options;
284
+ setSpec(options);
285
+ updateDataFromSpec(options);
286
+ };
287
+ window.addEventListener('spec', update);
288
+ return function () {
289
+ window.removeEventListener('spec', update);
290
+ };
291
+ });
292
+
176
293
  // 切换 tab
177
294
  var onTabChange = useCallback(function (tab) {
178
295
  setCurrentEditorTab(tab);
@@ -190,6 +307,52 @@ export var CodeEditor = function CodeEditor(_ref) {
190
307
  setCode(value);
191
308
  }
192
309
  }, [currentEditorTab]);
310
+ var parseFunction = function parseFunction(string) {
311
+ return string.replace(/"\<func\>(.*?)\<\/func\>"/g, function (_, code) {
312
+ return code;
313
+ });
314
+ };
315
+
316
+ // 序列化 JavaScript 对象的时候对 function 进行特殊的标注,
317
+ // 使得解析该字符串的时候能方便的提取 function 对应的字符串。
318
+ // { add: (x, y) => x + y } => '{ add: <func>(x, y) => x + y</func> }'
319
+ var withFunction = function withFunction(_, value) {
320
+ if (typeof value !== 'function') return value;
321
+ return "<func>".concat(value.toString().replace(/\n/g, ''), "</func>");
322
+ };
323
+ var languageOf = function languageOf(tab) {
324
+ switch (tab) {
325
+ case EDITOR_TABS.JAVASCRIPT:
326
+ case EDITOR_TABS.SPEC:
327
+ return 'javascript';
328
+ case EDITOR_TABS.DATA:
329
+ return 'json';
330
+ default:
331
+ return 'javascript';
332
+ }
333
+ };
334
+ var valueOf = function valueOf(tab) {
335
+ switch (tab) {
336
+ case EDITOR_TABS.JAVASCRIPT:
337
+ return code;
338
+ case EDITOR_TABS.SPEC:
339
+ return format(parseFunction("(".concat(JSON.stringify(spec, withFunction), ")")), {
340
+ plugins: [parserBabel]
341
+ });
342
+ case EDITOR_TABS.DATA:
343
+ return JSON.stringify(data, null, 2);
344
+ default:
345
+ return null;
346
+ }
347
+ };
348
+ var defaultOf = function defaultOf(tab) {
349
+ switch (tab) {
350
+ case EDITOR_TABS.JAVASCRIPT:
351
+ return code;
352
+ default:
353
+ return null;
354
+ }
355
+ };
193
356
  return /*#__PURE__*/React.createElement("div", {
194
357
  className: styles.editor
195
358
  }, /*#__PURE__*/React.createElement(Toolbar, {
@@ -206,33 +369,36 @@ export var CodeEditor = function CodeEditor(_ref) {
206
369
  },
207
370
  onEditorTabChange: onTabChange,
208
371
  onToggleFullscreen: onFullscreen
209
- }), /*#__PURE__*/React.createElement("div", {
210
- className: styles.monaco,
211
- style: {
212
- height: 'calc(100% - 36px)'
213
- }
214
- }, /*#__PURE__*/React.createElement(MonacoEditor, {
215
- language: currentEditorTab === EDITOR_TABS.JAVASCRIPT ? 'javascript' : 'json',
216
- value: currentEditorTab === EDITOR_TABS.JAVASCRIPT ? code : JSON.stringify(data, null, 2)
217
- // defaultValue={code}
218
- ,
219
- path: relativePath,
220
- loading: /*#__PURE__*/React.createElement(Loading, null),
221
- options: {
222
- readOnly: currentEditorTab === EDITOR_TABS.DATA,
223
- automaticLayout: true,
224
- minimap: {
225
- enabled: false
372
+ }), editorTabs.map(function (tab) {
373
+ return /*#__PURE__*/React.createElement("div", {
374
+ key: tab,
375
+ className: styles.monaco,
376
+ style: {
377
+ height: 'calc(100% - 36px)',
378
+ display: tab === currentEditorTab ? 'block' : 'none'
379
+ }
380
+ }, /*#__PURE__*/React.createElement(MonacoEditor, {
381
+ language: languageOf(tab),
382
+ value: valueOf(tab),
383
+ defaultValue: defaultOf(tab),
384
+ path: tab,
385
+ loading: /*#__PURE__*/React.createElement(Loading, null),
386
+ options: {
387
+ readOnly: tab === EDITOR_TABS.DATA || tab === EDITOR_TABS.SPEC,
388
+ automaticLayout: true,
389
+ minimap: {
390
+ enabled: false
391
+ },
392
+ scrollBeyondLastLine: false,
393
+ fixedOverflowWidgets: true,
394
+ lineNumbersMinChars: 4,
395
+ showFoldingControls: 'always',
396
+ foldingHighlight: true
226
397
  },
227
- scrollBeyondLastLine: false,
228
- fixedOverflowWidgets: true,
229
- lineNumbersMinChars: 4,
230
- showFoldingControls: 'always',
231
- foldingHighlight: true
232
- },
233
- onChange: onCodeChange,
234
- onMount: function onMount(editor) {
235
- monacoRef.current = editor;
236
- }
237
- })));
398
+ onChange: onCodeChange,
399
+ onMount: function onMount(editor) {
400
+ monacoRef.current = editor;
401
+ }
402
+ }));
403
+ }));
238
404
  };
@@ -39,4 +39,4 @@ export declare function execute(code: string, playgroundScriptContainer: string,
39
39
  /**
40
40
  * 编译代码
41
41
  */
42
- export declare function compile(value: string, relativePath: string): any;
42
+ export declare function compile(value: string, relativePath: string, es5?: boolean): any;
@@ -130,9 +130,10 @@ export function execute(code, playgroundScriptContainer, container) {
130
130
  * 编译代码
131
131
  */
132
132
  export function compile(value, relativePath) {
133
+ var es5 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
133
134
  var _transform = transform(value, {
134
135
  filename: relativePath,
135
- presets: ['react', 'typescript', 'es2015', ['stage-3', {
136
+ presets: ['react', 'typescript', es5 ? 'es2015' : 'es2016', ['stage-3', {
136
137
  decoratorsBeforeExport: true
137
138
  }]],
138
139
  plugins: ['transform-modules-umd']