dumi 2.0.4 → 2.0.6

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 (33) hide show
  1. package/compiled/_internal/searchWorker.min.js +1 -0
  2. package/dist/assetParsers/atom.d.ts +1 -0
  3. package/dist/assetParsers/atom.js +1 -1
  4. package/dist/client/theme-api/AtomRenderer.d.ts +8 -0
  5. package/dist/client/theme-api/AtomRenderer.js +99 -0
  6. package/dist/client/theme-api/DumiPage.js +2 -13
  7. package/dist/client/theme-api/context.d.ts +1 -0
  8. package/dist/client/theme-api/context.js +1 -0
  9. package/dist/client/theme-api/index.d.ts +1 -0
  10. package/dist/client/theme-api/index.js +1 -0
  11. package/dist/client/theme-api/useSiteSearch/index.d.ts +16 -1
  12. package/dist/client/theme-api/useSiteSearch/index.js +7 -2
  13. package/dist/client/typings.d.ts +14 -0
  14. package/dist/constants.d.ts +1 -0
  15. package/dist/constants.js +5 -3
  16. package/dist/features/assets.js +1 -1
  17. package/dist/features/derivative.js +9 -0
  18. package/dist/features/exports.js +1 -1
  19. package/dist/features/parser.js +5 -2
  20. package/dist/features/tabs.js +3 -3
  21. package/dist/features/theme/index.js +25 -6
  22. package/dist/loaders/markdown/index.js +1 -0
  23. package/dist/loaders/markdown/transformer/remarkContainer.d.ts +1 -1
  24. package/dist/loaders/markdown/transformer/remarkContainer.js +4 -0
  25. package/dist/preset.js +0 -13
  26. package/package.json +9 -8
  27. package/theme-default/layouts/DocLayout/index.js +27 -3
  28. package/theme-default/slots/RtlSwitch/index.less +6 -0
  29. package/theme-default/slots/SearchBar/index.less +5 -0
  30. package/theme-default/slots/Sidebar/index.less +2 -1
  31. package/theme-default/slots/Toc/index.js +3 -3
  32. package/dist/client/theme-api/useSiteSearch/worker.d.ts +0 -17
  33. package/dist/client/theme-api/useSiteSearch/worker.js +0 -318
@@ -0,0 +1 @@
1
+ "use strict";(()=>{var P=Object.create;var k=Object.defineProperty;var z=Object.getOwnPropertyDescriptor;var D=Object.getOwnPropertyNames,R=Object.getOwnPropertySymbols,B=Object.getPrototypeOf,E=Object.prototype.hasOwnProperty,L=Object.prototype.propertyIsEnumerable;var O=(i,e,n)=>e in i?k(i,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):i[e]=n,I=(i,e)=>{for(var n in e||(e={}))E.call(e,n)&&O(i,n,e[n]);if(R)for(var n of R(e))L.call(e,n)&&O(i,n,e[n]);return i};var N=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports);var F=(i,e,n,u)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of D(e))!E.call(i,r)&&r!==n&&k(i,r,{get:()=>e[r],enumerable:!(u=z(e,r))||u.enumerable});return i};var W=(i,e,n)=>(n=i!=null?P(B(i)):{},F(e||!i||!i.__esModule?k(n,"default",{value:i,enumerable:!0}):n,i));var j=N((K,w)=>{w.exports=function(i){var e={};function n(u){if(e[u])return e[u].exports;var r=e[u]={exports:{},id:u,loaded:!1};return i[u].call(r.exports,r,r.exports,n),r.loaded=!0,r.exports}return n.m=i,n.c=e,n.p="",n(0)}([function(i,e,n){i.exports=n(1)},function(i,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var u=n(2);Object.defineProperty(e,"combineChunks",{enumerable:!0,get:function(){return u.combineChunks}}),Object.defineProperty(e,"fillInChunks",{enumerable:!0,get:function(){return u.fillInChunks}}),Object.defineProperty(e,"findAll",{enumerable:!0,get:function(){return u.findAll}}),Object.defineProperty(e,"findChunks",{enumerable:!0,get:function(){return u.findChunks}})},function(i,e){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n=e.findAll=function(t){var g=t.autoEscape,c=t.caseSensitive,f=c===void 0?!1:c,d=t.findChunks,o=d===void 0?r:d,h=t.sanitize,v=t.searchWords,T=t.textToHighlight;return l({chunksToHighlight:u({chunks:o({autoEscape:g,caseSensitive:f,sanitize:h,searchWords:v,textToHighlight:T})}),totalLength:T?T.length:0})},u=e.combineChunks=function(t){var g=t.chunks;return g=g.sort(function(c,f){return c.start-f.start}).reduce(function(c,f){if(c.length===0)return[f];var d=c.pop();if(f.start<=d.end){var o=Math.max(d.end,f.end);c.push({highlight:!1,start:d.start,end:o})}else c.push(d,f);return c},[]),g},r=function(t){var g=t.autoEscape,c=t.caseSensitive,f=t.sanitize,d=f===void 0?p:f,o=t.searchWords,h=t.textToHighlight;return h=d(h),o.filter(function(v){return v}).reduce(function(v,T){T=d(T),g&&(T=a(T));for(var m=new RegExp(T,c?"g":"gi"),y=void 0;y=m.exec(h);){var S=y.index,$=m.lastIndex;$>S&&v.push({highlight:!1,start:S,end:$}),y.index===m.lastIndex&&m.lastIndex++}return v},[])};e.findChunks=r;var l=e.fillInChunks=function(t){var g=t.chunksToHighlight,c=t.totalLength,f=[],d=function(v,T,m){T-v>0&&f.push({start:v,end:T,highlight:m})};if(g.length===0)d(0,c,!1);else{var o=0;g.forEach(function(h){d(o,h.start,!1),d(h.start,h.end,!0),o=h.end}),d(o,c,!1)}return f};function p(s){return s}function a(s){return s.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}}])});var C=W(j()),H="tab";function M(i,e,n,u,r){let l=r!==void 0,p=u.reduce((a,s)=>(s.tocIndex===r&&(a[s.paraId]=(a[s.paraId]||"").concat(s.value)),a),[]).filter(Boolean);return Boolean(p.length)||l?{rawTitle:i,title:e,link:n,paragraphs:u.reduce((a,s)=>{var t,g;return s.tocIndex===r&&((g=a[t=s.paraId])!=null||(a[t]=""),a[s.paraId]+=s.value),a},[]).filter(Boolean)}:null}function x(i){return[i.title,i.subtitle].filter(Boolean).join(" ")}function _(i,e,n){let u=[],r=Object.values(e).reduce((l,p)=>{var a,s;return p.asset&&((s=l[a=p.routeId])!=null||(l[a]=[]),l[p.routeId].push(p)),l},{});return Object.values(i).forEach(l=>{var p;if("meta"in l&&!("isLayout"in l)){let a=l.meta,s=l.path.replace(/^([^/])/,"/$1")||"/",t=n.find(o=>s===o.link||s.startsWith(`${o.activePath}/`)),g=(r[l.id]||[]).map(o=>{var h;return(h=o.asset)==null?void 0:h.id}),c=M("",x(a.frontmatter),s,a.texts),f=a.toc.reduce((o,h,v)=>(!g.includes(h.id)&&h.depth>1&&o.push(M(h.title,`${x(a.frontmatter)} - ${h.title}`,`${s}#${h.id}`,a.texts,v)),o),[]),d=(a.tabs||[]).reduce((o,{key:h,meta:v})=>{let T=M("",`${x(a.frontmatter)} - ${v.frontmatter.title}`,`${s}?${H}=${h}`,v.texts);return T&&o.push(T),o.push(...v.toc.map((m,y)=>M(m.title,`${x(a.frontmatter)} - ${v.frontmatter.title} - ${m.title}`,`${s}?${H}=${h}#${m.id}`,v.texts,y))),o},[]);u.push({navTitle:t==null?void 0:t.title,navOrder:t?n.indexOf(t):1/0,title:x(a.frontmatter),link:s,sections:[...c?[c]:[],...f,...d],demos:((p=r[l.id])==null?void 0:p.map(o=>({link:`${s}#${o.asset.id}`,rawTitle:o.asset.title||"",title:o.asset.title||x(a.frontmatter),description:o.asset.description||"",keywords:o.asset.keywords||[]})))||[]})}}),u}function b(i="",e,n=1){let u=(0,C.findAll)({textToHighlight:i,searchWords:e,autoEscape:!0}),r={};return[u.map(({start:l,end:p,highlight:a},s)=>{let t={text:i.slice(l,p)};return s===0&&!a&&u.length>1&&t.text.length>20&&(t.text=`...${t.text.slice(-20)}`),a&&(t.highlighted=!0,r[e.find(g=>t.text.includes(g))]=n),t}),r]}function Y(i,e){let n=e.split(" "),u=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(" ","|"),"gi"),r={};return i.forEach(l=>{var a,s;let p=[];if(l.sections.forEach(t=>{for(let g of t.paragraphs)if(u.test(g)){let[c,f]=b(t.title,n,10),[d,o]=b(g,n);p.push({type:"content",link:t.link,priority:Object.values(I(I({},o),f)).reduce((h,v)=>h+v,0),highlightTitleTexts:c,highlightTexts:d});return}if(u.test(t.rawTitle)){let[g,c]=b(t.title,n,10);p.push({type:"title",link:t.link,priority:Object.values(c).reduce((f,d)=>f+d,0),highlightTitleTexts:g,highlightTexts:b(t.paragraphs[0]||"",n)[0]})}}),l.demos.forEach(t=>{if(u.test(t.rawTitle)||u.test(t.description)){let[g,c]=b(t.title,n,10),[f,d]=b(t.description,n);p.push({type:"demo",link:t.link,priority:Object.values(I(I({},d),c)).reduce((o,h)=>o+h,0),highlightTitleTexts:g,highlightTexts:f})}}),u.test(l.title)){let[t,g]=b(l.title,n,100);p.push({type:"page",link:l.link,priority:Object.values(g).reduce((c,f)=>c+f,0),highlightTitleTexts:t,highlightTexts:b(((a=l.sections[0])==null?void 0:a.paragraphs[0])||"",n)[0]})}if(p.length){let t=l.navTitle||"$ROOT";(s=r[t])!=null||(r[t]={title:l.navTitle,priority:l.navOrder*1e3,hints:[]}),r[t].hints.push(...p)}}),Object.values(r).forEach(({hints:l})=>{l.sort((p,a)=>a.priority-p.priority)}),Object.values(r).sort((l,p)=>p.priority-l.priority)}var A;self.onmessage=({data:i})=>{switch(i.action){case"generate-metadata":A=_(i.args.routes,i.args.demos,i.args.nav);break;case"get-search-result":self.postMessage(Y(A,i.args.keywords));break;default:}};})();
@@ -10,6 +10,7 @@ declare class AtomAssetsParser {
10
10
  constructor(opts: {
11
11
  entryFile: string;
12
12
  resolveDir: string;
13
+ unpkgHost?: string;
13
14
  watch?: boolean;
14
15
  });
15
16
  parse(): Promise<{
@@ -39,7 +39,7 @@ var AtomAssetsParser = class {
39
39
  this.parser = new import_parser.SchemaParser({
40
40
  entryPath: opts.entryFile,
41
41
  basePath: opts.resolveDir,
42
- unPkgHost: "https://unpkg.com"
42
+ unPkgHost: opts.unpkgHost ?? "https://unpkg.com"
43
43
  });
44
44
  }
45
45
  async parse() {
@@ -0,0 +1,8 @@
1
+ import { AtomAsset, ExamplePresetAsset } from 'dumi-assets-types';
2
+ import { type FC } from 'react';
3
+ interface IAtomRendererProps {
4
+ type: AtomAsset['type'];
5
+ value: ExamplePresetAsset['value'];
6
+ }
7
+ export declare const AtomRenderer: FC<IAtomRendererProps>;
8
+ export {};
@@ -0,0 +1,99 @@
1
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2
+
3
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
4
+
5
+ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
+
7
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
8
+
9
+ 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."); }
10
+
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); }
12
+
13
+ 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; }
14
+
15
+ function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
16
+
17
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
18
+
19
+ 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); }
20
+
21
+ import { useSiteData } from 'dumi';
22
+ import React from 'react';
23
+
24
+ function builtInProcessor(entity, entryExports) {
25
+ var mod;
26
+
27
+ switch (entity.$$__type) {
28
+ case 'function':
29
+ // eslint-disable-next-line no-eval
30
+ return eval(entity.$$__body.sourceCode);
31
+
32
+ case 'element':
33
+ // find child component from entry exports
34
+ mod = entity.$$__body.componentName.split('.').reduce(function (col, cur) {
35
+ return col[cur];
36
+ }, entryExports); // fallback to HTML tag
37
+
38
+ if (mod === undefined) return entity.$$__body.componentName; // support pure render for antd components
39
+
40
+ return '_InternalPanelDoNotUseOrYouWillBeFired' in mod ? mod._InternalPanelDoNotUseOrYouWillBeFired : mod;
41
+ }
42
+ }
43
+
44
+ function deepReplace(value, entityProcessor) {
45
+ // transform array props
46
+ if (Array.isArray(value)) {
47
+ return value.map(function (e) {
48
+ return deepReplace(e, entityProcessor);
49
+ });
50
+ } // transform element props
51
+
52
+
53
+ if (_typeof(value) === 'object' && (value === null || value === void 0 ? void 0 : value.$$__type) === 'element') {
54
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
55
+ return translatePresetToReact(value.$$__body, entityProcessor);
56
+ } // transform pure object props
57
+
58
+
59
+ if (_typeof(value) === 'object' && Object.prototype.toString.call(value) === '[object Object]') {
60
+ return Object.entries(value).reduce(function (col, _ref) {
61
+ var _ref2 = _slicedToArray(_ref, 2),
62
+ key = _ref2[0],
63
+ value = _ref2[1];
64
+
65
+ return _objectSpread(_objectSpread({}, col), {}, _defineProperty({}, key, deepReplace(value, entityProcessor)));
66
+ }, {});
67
+ }
68
+
69
+ return value;
70
+ }
71
+
72
+ function translatePresetToReact(value, processor) {
73
+ var props = value.props,
74
+ size = value.size;
75
+ var Component = processor({
76
+ $$__type: 'element',
77
+ $$__body: value
78
+ });
79
+ return /*#__PURE__*/React.createElement(Component, deepReplace(_objectSpread(_objectSpread({}, props), {}, {
80
+ style: _objectSpread(_objectSpread({}, props.style), size)
81
+ }), processor));
82
+ }
83
+
84
+ export var AtomRenderer = function AtomRenderer(props) {
85
+ var _useSiteData = useSiteData(),
86
+ entryExports = _useSiteData.entryExports;
87
+
88
+ switch (props.type) {
89
+ case 'COMPONENT':
90
+ return translatePresetToReact(props.value, function (entity) {
91
+ // TODO: support custom processor
92
+ return builtInProcessor(entity, entryExports);
93
+ });
94
+
95
+ default:
96
+ // TODO: handle FUNCTION type
97
+ return /*#__PURE__*/React.createElement(React.Fragment, null, props.type, " atom is not supported.");
98
+ }
99
+ };
@@ -10,14 +10,11 @@ function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Sy
10
10
 
11
11
  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
12
12
 
13
- import { useLocation, useRouteMeta, useSiteData } from 'dumi';
13
+ import { useRouteMeta, useSiteData } from 'dumi';
14
14
  import ContentTabs from "dumi/theme/slots/ContentTabs";
15
15
  import React, { useEffect, useState } from 'react';
16
16
  import { useTabQueryState } from "./useTabMeta";
17
17
  export var DumiPage = function DumiPage(props) {
18
- var _useLocation = useLocation(),
19
- hash = _useLocation.hash;
20
-
21
18
  var _useRouteMeta = useRouteMeta(),
22
19
  tabs = _useRouteMeta.tabs;
23
20
 
@@ -42,15 +39,7 @@ export var DumiPage = function DumiPage(props) {
42
39
 
43
40
  useEffect(function () {
44
41
  setLoading(false);
45
- }, []); // handle hash change
46
-
47
- useEffect(function () {
48
- var id = hash.replace('#', '');
49
- setTimeout(function () {
50
- var elm = id && document.getElementById(decodeURIComponent(id));
51
- if (elm) document.documentElement.scrollTo(0, elm.offsetTop - 80);
52
- }, 1);
53
- }, [hash]);
42
+ }, []);
54
43
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(ContentTabs, {
55
44
  tabs: tabs,
56
45
  tabKey: tabKey,
@@ -4,6 +4,7 @@ import { type ComponentType } from 'react';
4
4
  import type { ILocalesConfig, IPreviewerProps, IThemeConfig } from './types';
5
5
  interface ISiteContext {
6
6
  pkg: Partial<Record<keyof typeof PICKED_PKG_FIELDS, any>>;
7
+ entryExports: Record<string, any>;
7
8
  demos: Record<string, {
8
9
  component: ComponentType;
9
10
  asset: IPreviewerProps['asset'];
@@ -1,6 +1,7 @@
1
1
  import { createContext, useContext } from 'react';
2
2
  export var SiteContext = /*#__PURE__*/createContext({
3
3
  pkg: {},
4
+ entryExports: {},
4
5
  demos: {},
5
6
  components: {},
6
7
  locales: [],
@@ -1,4 +1,5 @@
1
1
  export { createIntlCache, defineMessages, FormattedDate, FormattedDateParts, FormattedDisplayName, FormattedList, FormattedMessage, FormattedNumber, FormattedNumberParts, FormattedPlural, FormattedRelativeTime, FormattedTime, FormattedTimeParts, injectIntl, IntlContext, IntlProvider, RawIntlProvider, useIntl, } from 'react-intl';
2
+ export { AtomRenderer } from './AtomRenderer';
2
3
  export { useSiteData } from './context';
3
4
  export { DumiDemo } from './DumiDemo';
4
5
  export { DumiDemoGrid } from './DumiDemoGrid';
@@ -1,4 +1,5 @@
1
1
  export { createIntlCache, defineMessages, FormattedDate, FormattedDateParts, FormattedDisplayName, FormattedList, FormattedMessage, FormattedNumber, FormattedNumberParts, FormattedPlural, FormattedRelativeTime, FormattedTime, FormattedTimeParts, injectIntl, IntlContext, IntlProvider, RawIntlProvider, useIntl } from 'react-intl';
2
+ export { AtomRenderer } from "./AtomRenderer";
2
3
  export { useSiteData } from "./context";
3
4
  export { DumiDemo } from "./DumiDemo";
4
5
  export { DumiDemoGrid } from "./DumiDemoGrid";
@@ -1,4 +1,19 @@
1
- import type { ISearchResult } from './worker';
1
+ export interface IHighlightText {
2
+ highlighted?: boolean;
3
+ text: string;
4
+ }
5
+ export interface ISearchNavResult {
6
+ title?: string;
7
+ priority: number;
8
+ hints: {
9
+ type: 'page' | 'title' | 'demo' | 'content';
10
+ link: string;
11
+ priority: number;
12
+ highlightTitleTexts: IHighlightText[];
13
+ highlightTexts: IHighlightText[];
14
+ }[];
15
+ }
16
+ export declare type ISearchResult = ISearchNavResult[];
2
17
  export declare const useSiteSearch: () => {
3
18
  keywords: string;
4
19
  setKeywords: (val: string) => void;
@@ -18,11 +18,16 @@ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
18
18
 
19
19
  import { useNavData, useSiteData } from 'dumi';
20
20
  import { useCallback, useEffect, useRef, useState } from 'react';
21
- import { useLocaleDocRoutes } from "../utils";
21
+ import { useLocaleDocRoutes } from "../utils"; // @ts-ignore
22
+
23
+ import workerCode from '-!../../../../compiled/_internal/searchWorker.min?dumi-raw';
22
24
  var worker; // for ssr
23
25
 
24
26
  if (typeof window !== 'undefined') {
25
- worker = new Worker(new URL('./worker', import.meta.url));
27
+ // use blob to avoid generate entry(chunk) for worker
28
+ worker = new Worker(URL.createObjectURL(new Blob([workerCode], {
29
+ type: 'application/javascript'
30
+ })));
26
31
  }
27
32
 
28
33
  export var useSiteSearch = function useSiteSearch() {
@@ -0,0 +1,14 @@
1
+ declare module '*.less' {
2
+ const classes: CSSModuleClasses;
3
+ export default classes;
4
+ }
5
+
6
+ declare module '*.svg' {
7
+ import * as React from 'react';
8
+ export const ReactComponent: React.FunctionComponent<
9
+ React.SVGProps<SVGSVGElement> & { title?: string }
10
+ >;
11
+
12
+ const src: string;
13
+ export default src;
14
+ }
@@ -13,3 +13,4 @@ export declare const PICKED_PKG_FIELDS: {
13
13
  authors: string;
14
14
  };
15
15
  export declare const CLIENT_DEPS: string[];
16
+ export declare const USELESS_TMP_FILES: string[];
package/dist/constants.js CHANGED
@@ -25,7 +25,8 @@ __export(constants_exports, {
25
25
  LOCAL_THEME_DIR: () => LOCAL_THEME_DIR,
26
26
  PICKED_PKG_FIELDS: () => PICKED_PKG_FIELDS,
27
27
  SP_ROUTE_PREFIX: () => SP_ROUTE_PREFIX,
28
- THEME_PREFIX: () => THEME_PREFIX
28
+ THEME_PREFIX: () => THEME_PREFIX,
29
+ USELESS_TMP_FILES: () => USELESS_TMP_FILES
29
30
  });
30
31
  module.exports = __toCommonJS(constants_exports);
31
32
  var LOCAL_DUMI_DIR = ".dumi";
@@ -46,7 +47,6 @@ var CLIENT_DEPS = [
46
47
  "@ant-design/icons-svg",
47
48
  "@makotot/ghostui",
48
49
  "deepmerge",
49
- "highlight-words-core",
50
50
  "lodash.throttle",
51
51
  "prism-react-renderer",
52
52
  "prismjs",
@@ -54,6 +54,7 @@ var CLIENT_DEPS = [
54
54
  "react-copy-to-clipboard",
55
55
  "react-intl"
56
56
  ];
57
+ var USELESS_TMP_FILES = ["tsconfig.json", "typings.d.ts"];
57
58
  // Annotate the CommonJS export names for ESM import in node:
58
59
  0 && (module.exports = {
59
60
  CLIENT_DEPS,
@@ -62,5 +63,6 @@ var CLIENT_DEPS = [
62
63
  LOCAL_THEME_DIR,
63
64
  PICKED_PKG_FIELDS,
64
65
  SP_ROUTE_PREFIX,
65
- THEME_PREFIX
66
+ THEME_PREFIX,
67
+ USELESS_TMP_FILES
66
68
  });
@@ -50,7 +50,7 @@ var assets_default = (api) => {
50
50
  enableBy: ({ env }) => env === "production" && Boolean(api.args.assets)
51
51
  });
52
52
  api.onBuildComplete(async () => {
53
- const { components } = await api.service.atomParser.parse();
53
+ const { components } = api.service.atomParser ? await api.service.atomParser.parse() : { components: {} };
54
54
  const assets = await api.applyPlugins({
55
55
  key: "modifyAssetsMetadata",
56
56
  initialValue: {
@@ -121,6 +121,15 @@ var derivative_default = (api) => {
121
121
  }
122
122
  }
123
123
  });
124
+ api.register({
125
+ key: "onGenerateFiles",
126
+ stage: Infinity,
127
+ fn() {
128
+ import_constants.USELESS_TMP_FILES.forEach((file) => {
129
+ import_plugin_utils.fsExtra.rmSync(import_path.default.join(api.paths.absTmpPath, file), { force: true });
130
+ });
131
+ }
132
+ });
124
133
  api.registerPlugins([require.resolve("../../compiled/@umijs/plugins")]);
125
134
  };
126
135
  // Annotate the CommonJS export names for ESM import in node:
@@ -36,7 +36,7 @@ var exports_default = (api) => {
36
36
  api.writeTmpFile({
37
37
  noPluginDir: true,
38
38
  path: "dumi/exports.ts",
39
- content: `export * from '../exports.ts';
39
+ content: `export * from '../exports';
40
40
  export * from '${(0, import_plugin_utils.winPath)(require.resolve("../client/theme-api"))}';`
41
41
  });
42
42
  });
@@ -39,7 +39,9 @@ var parser_default = (api) => {
39
39
  key: "apiParser",
40
40
  enableBy: api.EnableBy.config,
41
41
  config: {
42
- schema: (Joi) => Joi.object()
42
+ schema: (Joi) => Joi.object({
43
+ unpkgHost: Joi.string().uri()
44
+ })
43
45
  }
44
46
  });
45
47
  api.modifyDefaultConfig((memo) => {
@@ -54,7 +56,8 @@ var parser_default = (api) => {
54
56
  } = require("../assetParsers/atom");
55
57
  api.service.atomParser = new AtomAssetsParser({
56
58
  entryFile: api.config.resolve.entryFile,
57
- resolveDir: api.cwd
59
+ resolveDir: api.cwd,
60
+ unpkgHost: api.config.apiParser.unpkgHost
58
61
  });
59
62
  if (api.env === "development") {
60
63
  api.service.atomParser.watch(writeAtomsMetaFile);
@@ -47,7 +47,7 @@ var tabs_default = (api) => {
47
47
  key: "addContentTab"
48
48
  });
49
49
  tabsFromPlugins.forEach((tab) => {
50
- tab.id ?? (tab.id = `plugin-tab${tab.test ? `-${tab.test}` : ""}-${tab.key}`);
50
+ tab.id ?? (tab.id = `plugin-tab-${tab.key}`);
51
51
  tab.component = (0, import_plugin_utils.winPath)(tab.component);
52
52
  });
53
53
  return memo;
@@ -82,8 +82,8 @@ var tabs_default = (api) => {
82
82
  });
83
83
  }
84
84
  });
85
- tabs.push(...tabsFromPlugins.map((tab) => ({
86
- index: tabs.length,
85
+ tabs.push(...tabsFromPlugins.map((tab, index) => ({
86
+ index: tabs.length + index,
87
87
  key: tab.key,
88
88
  id: tab.id,
89
89
  file: tab.component
@@ -42,6 +42,12 @@ function getPkgThemePath(api) {
42
42
  const pkgThemeName = getPkgThemeName(api);
43
43
  return pkgThemeName && import_path.default.dirname(require.resolve(`${pkgThemeName}/package.json`, { paths: [api.cwd] }));
44
44
  }
45
+ function getModuleExports(modulePath) {
46
+ return (0, import_bundler_utils.parseModuleSync)({
47
+ path: modulePath,
48
+ content: import_fs.default.readFileSync(modulePath, "utf-8")
49
+ })[1];
50
+ }
45
51
  var theme_default = (api) => {
46
52
  const defaultThemeData = (0, import_loader.default)(DEFAULT_THEME_PATH);
47
53
  const pkgThemePath = getPkgThemePath(api);
@@ -60,7 +66,11 @@ var theme_default = (api) => {
60
66
  api.registerPlugins([plugin]);
61
67
  }
62
68
  });
63
- (0, import_derivative.safeExcludeInMFSU)(api, ["dumi/theme-default", "@ant-design/icons-svg", getPkgThemeName(api)].filter(Boolean).map((pkg) => new RegExp(pkg)));
69
+ (0, import_derivative.safeExcludeInMFSU)(api, [
70
+ "dumi/theme-default",
71
+ "@ant-design/icons-svg",
72
+ getPkgThemeName(api)
73
+ ].filter(Boolean).map((pkg) => new RegExp(pkg)));
64
74
  api.register({
65
75
  key: "modifyAppData",
66
76
  before: "appData",
@@ -113,10 +123,7 @@ var theme_default = (api) => {
113
123
  if (item.source === "dumi")
114
124
  return;
115
125
  let contents = [];
116
- const [, exports] = (0, import_bundler_utils.parseModuleSync)({
117
- path: item.source,
118
- content: import_fs.default.readFileSync(item.source, "utf-8")
119
- });
126
+ const exports = getModuleExports(item.source);
120
127
  if (exports.includes("default")) {
121
128
  contents.push(`export { default } from '${item.source}';`);
122
129
  }
@@ -130,6 +137,10 @@ var theme_default = (api) => {
130
137
  });
131
138
  });
132
139
  });
140
+ const entryFile = api.config.resolve.entryFile && [import_path.default.resolve(api.cwd, api.config.resolve.entryFile)].find(import_fs.default.existsSync);
141
+ const entryExports = entryFile ? getModuleExports(entryFile) : [];
142
+ const hasDefaultExport = entryExports.includes("default");
143
+ const hasNamedExport = entryExports.some((exp) => exp !== "default");
133
144
  api.writeTmpFile({
134
145
  noPluginDir: true,
135
146
  path: "dumi/theme/ContextWrapper.tsx",
@@ -137,7 +148,14 @@ var theme_default = (api) => {
137
148
  import { useOutlet, history } from 'dumi';
138
149
  import { SiteContext } from '${(0, import_plugin_utils.winPath)(require.resolve("../../client/theme-api/context"))}';
139
150
  import { demos, components } from '../meta';
140
- import { locales } from '../locales/config';
151
+ import { locales } from '../locales/config';${hasDefaultExport ? `
152
+ import entryDefaultExport from '${(0, import_plugin_utils.winPath)(entryFile)}';` : ""}${hasNamedExport ? `
153
+ import * as entryMemberExports from '${(0, import_plugin_utils.winPath)(entryFile)}';` : ""}
154
+
155
+ const entryExports = {
156
+ ${hasDefaultExport ? "default: entryDefaultExport," : ""}
157
+ ${hasNamedExport ? "...entryMemberExports," : ""}
158
+ };
141
159
 
142
160
  export default function DumiContextWrapper() {
143
161
  const outlet = useOutlet();
@@ -160,6 +178,7 @@ export default function DumiContextWrapper() {
160
178
  return (
161
179
  <SiteContext.Provider value={{
162
180
  pkg: ${JSON.stringify(import_plugin_utils.lodash.pick(api.pkg, ...Object.keys(import_constants.PICKED_PKG_FIELDS)))},
181
+ entryExports,
163
182
  demos,
164
183
  components,
165
184
  locales,
@@ -137,6 +137,7 @@ function mdLoader(content) {
137
137
  ].join(":");
138
138
  cache.setSync(finalCacheKey, ret);
139
139
  cb(null, emit.call(this, opts, ret));
140
+ delete deferrer[cacheKey];
140
141
  }).catch(cb);
141
142
  }
142
143
  // Annotate the CommonJS export names for ESM import in node:
@@ -1,3 +1,3 @@
1
1
  import type { Root } from 'mdast';
2
2
  import type { Transformer } from 'unified';
3
- export default function remarkContainer(): Transformer<Root>;
3
+ export default function remarkContainer(this: any): Transformer<Root>;
@@ -32,6 +32,10 @@ var VALID_CONTAINER_TYPES = ["info", "warning", "success", "error"];
32
32
  ({ visit, SKIP } = await import("unist-util-visit"));
33
33
  })();
34
34
  function remarkContainer() {
35
+ const data = this.data();
36
+ const micromarkExtensions = data.micromarkExtensions.find(({ flow, text }) => flow && "58" in flow && text && "58" in text);
37
+ delete micromarkExtensions.text;
38
+ micromarkExtensions.flow["58"].splice(1, 1);
35
39
  return (tree) => {
36
40
  visit(tree, (node, i, parent) => {
37
41
  if (node.type === "containerDirective" && VALID_CONTAINER_TYPES.includes(node.name)) {
package/dist/preset.js CHANGED
@@ -25,21 +25,8 @@ __export(preset_exports, {
25
25
  default: () => preset_default
26
26
  });
27
27
  module.exports = __toCommonJS(preset_exports);
28
- var import_fs = __toESM(require("fs"));
29
- var import_path = __toESM(require("path"));
30
- var import_plugin_utils = require("umi/plugin-utils");
31
28
  var preset_default = (api) => {
32
29
  api.describe({ key: "dumi-preset" });
33
- const legacyConfig = [
34
- ".umirc.ts",
35
- ".umirc.js",
36
- "config/config.ts",
37
- "config/config.js"
38
- ].find((file) => import_fs.default.existsSync(import_path.default.join(api.cwd, file)));
39
- if (legacyConfig) {
40
- import_plugin_utils.logger.warn(`Detected you are using legacy config file \`${legacyConfig}\`, it will no longer be loaded, please migrate to the new \`.dumirc.ts\` file, and the tmp file also from \`.umi\` to \`.dumi/tmp\`, please update related files such as \`.gitignore\`, \`tsconfig.json\` & etc.`);
41
- import_plugin_utils.logger.warn(`\u68C0\u6D4B\u5230\u4F60\u5728\u4F7F\u7528\u65E7\u914D\u7F6E\u6587\u4EF6 \`${legacyConfig}\`\uFF0C\u5B83\u5DF2\u4E0D\u518D\u751F\u6548\uFF0C\u8BF7\u5C06\u5185\u5BB9\u8FC1\u79FB\u5230\u65B0\u7684 \`.dumirc.ts\` \u914D\u7F6E\u6587\u4EF6\u4E2D\uFF0C\u53E6\u5916\u4E34\u65F6\u6587\u4EF6\u5939\u4E5F\u4ECE \`.umi\` \u8FC1\u79FB\u5230 \`.dumi/tmp\`\uFF0C\u8BF7\u540C\u65F6\u66F4\u65B0\u76F8\u5173\u6587\u4EF6\u5982 \`.gitignore\`\u3001\`tsconfig.json\` \u7B49`);
42
- }
43
30
  return {
44
31
  plugins: [
45
32
  require.resolve("./registerMethods"),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dumi",
3
- "version": "2.0.4",
3
+ "version": "2.0.6",
4
4
  "description": "📖 Documentation Generator of React Component",
5
5
  "keywords": [
6
6
  "generator",
@@ -36,7 +36,7 @@
36
36
  ],
37
37
  "scripts": {
38
38
  "build": "father build",
39
- "build:deps": "father prebundle",
39
+ "build:deps": "node scripts/pre-bundle-worker.js && father prebundle",
40
40
  "custom-install": "pnpm i",
41
41
  "dev": "father dev",
42
42
  "docs:build": "node ./bin/dumi.js build",
@@ -79,11 +79,12 @@
79
79
  "@swc/core": "^1.2.224",
80
80
  "@types/hast": "^2.3.4",
81
81
  "@types/mdast": "^3.0.10",
82
- "@umijs/bundler-utils": "^4.0.32",
83
- "@umijs/core": "^4.0.32",
82
+ "@umijs/bundler-utils": "^4.0.33",
83
+ "@umijs/core": "^4.0.33",
84
+ "animated-scroll-to": "^2.3.0",
84
85
  "codesandbox": "^2.2.3",
85
86
  "deepmerge": "^4.2.2",
86
- "dumi-afx-deps": "^1.0.0-alpha.1",
87
+ "dumi-afx-deps": "^1.0.0-alpha.2",
87
88
  "dumi-assets-types": "2.0.0-alpha.0",
88
89
  "enhanced-resolve": "^5.10.0",
89
90
  "estree-util-to-js": "^1.1.0",
@@ -95,7 +96,6 @@
95
96
  "hast-util-to-estree": "^2.1.0",
96
97
  "hast-util-to-string": "^2.0.0",
97
98
  "heti": "^0.9.2",
98
- "highlight-words-core": "^1.2.2",
99
99
  "html-to-text": "^8.2.1",
100
100
  "js-yaml": "^4.1.0",
101
101
  "lodash.throttle": "^4.1.1",
@@ -120,7 +120,7 @@
120
120
  "remark-rehype": "^10.1.0",
121
121
  "sass": "^1.55.0",
122
122
  "sitemap": "^7.1.1",
123
- "umi": "^4.0.32",
123
+ "umi": "^4.0.33",
124
124
  "unified": "^10.1.2",
125
125
  "unist-util-visit": "^4.1.0",
126
126
  "unist-util-visit-parents": "^5.1.1",
@@ -139,10 +139,11 @@
139
139
  "@types/pluralize": "^0.0.29",
140
140
  "@types/react": "^18.0.16",
141
141
  "@types/react-copy-to-clipboard": "^5.0.4",
142
- "@umijs/lint": "^4.0.32",
142
+ "@umijs/lint": "^4.0.33",
143
143
  "@umijs/plugins": "4.0.32",
144
144
  "eslint": "^8.20.0",
145
145
  "father": "^4.1.0",
146
+ "highlight-words-core": "^1.2.2",
146
147
  "husky": "^8.0.1",
147
148
  "lint-staged": "^13.0.3",
148
149
  "prettier": "^2.7.1",
@@ -11,7 +11,8 @@ function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Sy
11
11
  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
12
12
 
13
13
  import { ReactComponent as IconSidebar } from '@ant-design/icons-svg/inline-svg/outlined/align-left.svg';
14
- import { Helmet, useIntl, useOutlet, useRouteMeta, useSidebarData } from 'dumi';
14
+ import animateScrollTo from 'animated-scroll-to';
15
+ import { Helmet, useIntl, useLocation, useOutlet, useRouteMeta, useSidebarData, useSiteData } from 'dumi';
15
16
  import Content from "dumi/theme/slots/Content";
16
17
  import Features from "dumi/theme/slots/Features";
17
18
  import Footer from "dumi/theme/slots/Footer";
@@ -19,7 +20,7 @@ import Header from "dumi/theme/slots/Header";
19
20
  import Hero from "dumi/theme/slots/Hero";
20
21
  import Sidebar from "dumi/theme/slots/Sidebar";
21
22
  import Toc from "dumi/theme/slots/Toc";
22
- import React, { useState } from 'react';
23
+ import React, { useEffect, useState } from 'react';
23
24
  import "./index.less";
24
25
 
25
26
  var DocLayout = function DocLayout() {
@@ -27,14 +28,37 @@ var DocLayout = function DocLayout() {
27
28
  var outlet = useOutlet();
28
29
  var sidebar = useSidebarData();
29
30
 
31
+ var _useLocation = useLocation(),
32
+ hash = _useLocation.hash;
33
+
34
+ var _useSiteData = useSiteData(),
35
+ loading = _useSiteData.loading;
36
+
30
37
  var _useState = useState(false),
31
38
  _useState2 = _slicedToArray(_useState, 2),
32
39
  showSidebar = _useState2[0],
33
40
  setShowSidebar = _useState2[1];
34
41
 
35
42
  var _useRouteMeta = useRouteMeta(),
36
- fm = _useRouteMeta.frontmatter;
43
+ fm = _useRouteMeta.frontmatter; // handle hash change or visit page hash after async chunk loaded
44
+
37
45
 
46
+ useEffect(function () {
47
+ var id = hash.replace('#', '');
48
+
49
+ if (id) {
50
+ setTimeout(function () {
51
+ var elm = document.getElementById(decodeURIComponent(id));
52
+
53
+ if (elm) {
54
+ // animated-scroll-to instead of native scroll
55
+ animateScrollTo(elm.offsetTop - 80, {
56
+ maxDuration: 300
57
+ });
58
+ }
59
+ }, 1);
60
+ }
61
+ }, [loading, hash]);
38
62
  return /*#__PURE__*/React.createElement("div", {
39
63
  className: "dumi-default-doc-layout",
40
64
  "data-mobile-sidebar-active": showSidebar || undefined,
@@ -1,5 +1,11 @@
1
1
  @import '../LangSwitch/index.less';
2
2
 
3
+ .@{prefix}-lang-switch {
4
+ + & {
5
+ margin-inline-start: 20px;
6
+ }
7
+ }
8
+
3
9
  html[data-direction='rtl'] {
4
10
  direction: rtl;
5
11
  }
@@ -130,6 +130,9 @@
130
130
  box-sizing: border-box;
131
131
  box-shadow: inset 1px 1px 0 0 hsl(0deg 0% 100% / 50%), 0 3px 8px 0 #555a64;
132
132
  border-radius: 8px;
133
+ max-height: calc(100% - 120px);
134
+ display: flex;
135
+ flex-direction: column;
133
136
  }
134
137
 
135
138
  .@{prefix}-search-bar-input {
@@ -140,6 +143,8 @@
140
143
  .@{prefix}-search-result {
141
144
  min-height: 60px;
142
145
  margin-top: 12px;
146
+ flex: auto;
147
+ overflow: auto;
143
148
 
144
149
  > dl > dd {
145
150
  margin: 0 auto;
@@ -50,12 +50,13 @@
50
50
 
51
51
  > dd {
52
52
  margin: 0;
53
- padding: 10px 0;
53
+ padding: 8px 0;
54
54
 
55
55
  > a {
56
56
  display: block;
57
57
  color: @c-text-secondary;
58
58
  font-size: 16px;
59
+ line-height: 20px;
59
60
  text-decoration: none;
60
61
  transition: all 0.3s;
61
62
  white-space: nowrap;
@@ -13,7 +13,7 @@ function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Sy
13
13
  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
14
14
 
15
15
  import { Scrollspy as ScrollSpy } from '@makotot/ghostui/src/Scrollspy';
16
- import { useLocation, useRouteMeta, useSiteData } from 'dumi';
16
+ import { Link, useLocation, useRouteMeta, useSiteData } from 'dumi';
17
17
  import React, { useEffect, useRef, useState } from 'react';
18
18
  import "./index.less";
19
19
 
@@ -68,8 +68,8 @@ var Toc = function Toc() {
68
68
  return /*#__PURE__*/React.createElement("li", {
69
69
  key: item.id,
70
70
  "data-depth": item.depth
71
- }, /*#__PURE__*/React.createElement("a", _extends({
72
- href: link,
71
+ }, /*#__PURE__*/React.createElement(Link, _extends({
72
+ to: link,
73
73
  title: item.title
74
74
  }, activeIndex === i ? {
75
75
  className: 'active'
@@ -1,17 +0,0 @@
1
- interface IHighlightText {
2
- highlighted?: boolean;
3
- text: string;
4
- }
5
- interface ISearchNavResult {
6
- title?: string;
7
- priority: number;
8
- hints: {
9
- type: 'page' | 'title' | 'demo' | 'content';
10
- link: string;
11
- priority: number;
12
- highlightTitleTexts: IHighlightText[];
13
- highlightTexts: IHighlightText[];
14
- }[];
15
- }
16
- export declare type ISearchResult = ISearchNavResult[];
17
- export {};
@@ -1,318 +0,0 @@
1
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2
-
3
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
4
-
5
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
-
7
- function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
8
-
9
- 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."); }
10
-
11
- function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
12
-
13
- function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
14
-
15
- function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
16
-
17
- function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
18
-
19
- 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."); }
20
-
21
- 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); }
22
-
23
- function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
24
-
25
- function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
26
-
27
- 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; }
28
-
29
- import { findAll } from 'highlight-words-core';
30
- var TAB_QUERY_KEY = 'tab';
31
-
32
- function createMetadataSection(rawTitle, title, link, texts, tocIndex) {
33
- var allowEmptyParas = tocIndex !== undefined;
34
- var paragraphs = texts.reduce(function (acc, text) {
35
- if (text.tocIndex === tocIndex) {
36
- acc[text.paraId] = (acc[text.paraId] || '').concat(text.value);
37
- }
38
-
39
- return acc;
40
- }, []).filter(Boolean);
41
- return Boolean(paragraphs.length) || allowEmptyParas ? {
42
- rawTitle: rawTitle,
43
- title: title,
44
- link: link,
45
- paragraphs: texts.reduce(function (acc, text) {
46
- if (text.tocIndex === tocIndex) {
47
- var _text$paraId, _acc$_text$paraId;
48
-
49
- (_acc$_text$paraId = acc[_text$paraId = text.paraId]) !== null && _acc$_text$paraId !== void 0 ? _acc$_text$paraId : acc[_text$paraId] = '';
50
- acc[text.paraId] += text.value;
51
- }
52
-
53
- return acc;
54
- }, []).filter(Boolean)
55
- } : null;
56
- }
57
-
58
- function generateRouteTitle(fm) {
59
- return [fm.title, fm.subtitle].filter(Boolean).join(' ');
60
- }
61
-
62
- function generateSearchMetadata(routes, demos, nav) {
63
- var metadata = []; // generate demos mapping by route.id
64
-
65
- var demosMapping = Object.values(demos).reduce(function (acc, demo) {
66
- if (demo.asset) {
67
- var _demo$routeId, _acc$_demo$routeId;
68
-
69
- (_acc$_demo$routeId = acc[_demo$routeId = demo.routeId]) !== null && _acc$_demo$routeId !== void 0 ? _acc$_demo$routeId : acc[_demo$routeId] = [];
70
- acc[demo.routeId].push(demo);
71
- }
72
-
73
- return acc;
74
- }, {});
75
- Object.values(routes).forEach(function (route) {
76
- // only process content route
77
- if ('meta' in route && !('isLayout' in route)) {
78
- var _demosMapping$route$i;
79
-
80
- var routeMeta = route.meta;
81
- var routeAbsPath = route.path.replace(/^([^/])/, '/$1') || '/';
82
- var routeNav = nav.find(function (item) {
83
- return routeAbsPath === item.link || routeAbsPath.startsWith("".concat(item.activePath, "/"));
84
- });
85
- var demoIds = (demosMapping[route.id] || []).map(function (demo) {
86
- var _demo$asset;
87
-
88
- return (_demo$asset = demo.asset) === null || _demo$asset === void 0 ? void 0 : _demo$asset.id;
89
- });
90
- var orphanSection = createMetadataSection('', generateRouteTitle(routeMeta.frontmatter), routeAbsPath, routeMeta.texts);
91
- var tocSections = routeMeta.toc.reduce(function (acc, toc, i) {
92
- // exclude demo id, to avoid duplicate
93
- if (!demoIds.includes(toc.id) && toc.depth > 1) {
94
- acc.push(createMetadataSection(toc.title, "".concat(generateRouteTitle(routeMeta.frontmatter), " - ").concat(toc.title), "".concat(routeAbsPath, "#").concat(toc.id), routeMeta.texts, i));
95
- }
96
-
97
- return acc;
98
- }, []);
99
- var tabSections = (routeMeta.tabs || []).reduce(function (acc, _ref) {
100
- var key = _ref.key,
101
- meta = _ref.meta;
102
- // collect orphan section that not in toc
103
- var tabOrphanSection = createMetadataSection('', "".concat(generateRouteTitle(routeMeta.frontmatter), " - ").concat(meta.frontmatter.title), "".concat(routeAbsPath, "?").concat(TAB_QUERY_KEY, "=").concat(key), meta.texts);
104
- if (tabOrphanSection) acc.push(tabOrphanSection); // collect sections by toc
105
-
106
- acc.push.apply(acc, _toConsumableArray(meta.toc.map(function (toc, i) {
107
- return createMetadataSection(toc.title, "".concat(generateRouteTitle(routeMeta.frontmatter), " - ").concat(meta.frontmatter.title, " - ").concat(toc.title), "".concat(routeAbsPath, "?").concat(TAB_QUERY_KEY, "=").concat(key, "#").concat(toc.id), meta.texts, i);
108
- })));
109
- return acc;
110
- }, []);
111
- metadata.push({
112
- navTitle: routeNav === null || routeNav === void 0 ? void 0 : routeNav.title,
113
- navOrder: routeNav ? nav.indexOf(routeNav) : Infinity,
114
- title: generateRouteTitle(routeMeta.frontmatter),
115
- link: routeAbsPath,
116
- sections: [].concat(_toConsumableArray(orphanSection ? [orphanSection] : []), _toConsumableArray(tocSections), _toConsumableArray(tabSections)),
117
- demos: ((_demosMapping$route$i = demosMapping[route.id]) === null || _demosMapping$route$i === void 0 ? void 0 : _demosMapping$route$i.map(function (demo) {
118
- return {
119
- link: "".concat(routeAbsPath, "#").concat(demo.asset.id),
120
- rawTitle: demo.asset.title || '',
121
- title: demo.asset.title || generateRouteTitle(routeMeta.frontmatter),
122
- description: demo.asset.description || '',
123
- keywords: demo.asset.keywords || []
124
- };
125
- })) || []
126
- });
127
- }
128
- });
129
- return metadata;
130
- }
131
-
132
- function generateHighlightTexts() {
133
- var str = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
134
- var keywords = arguments.length > 1 ? arguments[1] : undefined;
135
- var priority = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1;
136
- var chunks = findAll({
137
- textToHighlight: str,
138
- searchWords: keywords,
139
- autoEscape: true
140
- }); // save matched keywords
141
-
142
- var matchedMapping = {};
143
- return [chunks.map(function (_ref2, i) {
144
- var start = _ref2.start,
145
- end = _ref2.end,
146
- highlight = _ref2.highlight;
147
- var highlightText = {
148
- text: str.slice(start, end)
149
- }; // omit long str before the first highlighted text
150
-
151
- if (i === 0 && !highlight && chunks.length > 1 && highlightText.text.length > 20) {
152
- highlightText.text = "...".concat(highlightText.text.slice(-20));
153
- } // mark highlight
154
-
155
-
156
- if (highlight) {
157
- highlightText.highlighted = true;
158
- matchedMapping[keywords.find(function (k) {
159
- return highlightText.text.includes(k);
160
- })] = priority;
161
- }
162
-
163
- return highlightText;
164
- }), matchedMapping];
165
- }
166
-
167
- function generateSearchResult(metadata, keywordsStr) {
168
- var keywords = keywordsStr.split(' ');
169
- var matchReg = new RegExp(keywordsStr.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(' ', '|'), 'gi');
170
- var resultMapping = {}; // traverse metadata from all routes
171
-
172
- metadata.forEach(function (data) {
173
- var hints = []; // find content & section hints
174
-
175
- data.sections.forEach(function (sec) {
176
- // find matched keywords in paragraph
177
- var _iterator = _createForOfIteratorHelper(sec.paragraphs),
178
- _step;
179
-
180
- try {
181
- for (_iterator.s(); !(_step = _iterator.n()).done;) {
182
- var p = _step.value;
183
-
184
- if (matchReg.test(p)) {
185
- var _generateHighlightTex3 = generateHighlightTexts(sec.title, keywords, 10),
186
- _generateHighlightTex4 = _slicedToArray(_generateHighlightTex3, 2),
187
- _highlightTitleTexts = _generateHighlightTex4[0],
188
- _titleMatchMapping = _generateHighlightTex4[1];
189
-
190
- var _generateHighlightTex5 = generateHighlightTexts(p, keywords),
191
- _generateHighlightTex6 = _slicedToArray(_generateHighlightTex5, 2),
192
- highlightTexts = _generateHighlightTex6[0],
193
- matchMapping = _generateHighlightTex6[1];
194
-
195
- hints.push({
196
- type: 'content',
197
- link: sec.link,
198
- priority: Object.values(_objectSpread(_objectSpread({}, matchMapping), _titleMatchMapping)).reduce(function (acc, p) {
199
- return acc + p;
200
- }, 0),
201
- highlightTitleTexts: _highlightTitleTexts,
202
- highlightTexts: highlightTexts
203
- }); // match at most once in the same section
204
-
205
- return;
206
- }
207
- } // find matched keywords in section title
208
-
209
- } catch (err) {
210
- _iterator.e(err);
211
- } finally {
212
- _iterator.f();
213
- }
214
-
215
- if (matchReg.test(sec.rawTitle)) {
216
- var _generateHighlightTex = generateHighlightTexts(sec.title, keywords, 10),
217
- _generateHighlightTex2 = _slicedToArray(_generateHighlightTex, 2),
218
- highlightTitleTexts = _generateHighlightTex2[0],
219
- titleMatchMapping = _generateHighlightTex2[1];
220
-
221
- hints.push({
222
- type: 'title',
223
- link: sec.link,
224
- priority: Object.values(titleMatchMapping).reduce(function (acc, p) {
225
- return acc + p;
226
- }, 0),
227
- highlightTitleTexts: highlightTitleTexts,
228
- highlightTexts: generateHighlightTexts(sec.paragraphs[0] || '', keywords)[0]
229
- });
230
- }
231
- }); // find demo hints
232
-
233
- data.demos.forEach(function (demo) {
234
- if (matchReg.test(demo.rawTitle) || matchReg.test(demo.description)) {
235
- var _generateHighlightTex7 = generateHighlightTexts(demo.title, keywords, 10),
236
- _generateHighlightTex8 = _slicedToArray(_generateHighlightTex7, 2),
237
- highlightTitleTexts = _generateHighlightTex8[0],
238
- titleMatchMapping = _generateHighlightTex8[1];
239
-
240
- var _generateHighlightTex9 = generateHighlightTexts(demo.description, keywords),
241
- _generateHighlightTex10 = _slicedToArray(_generateHighlightTex9, 2),
242
- highlightTexts = _generateHighlightTex10[0],
243
- matchMapping = _generateHighlightTex10[1];
244
-
245
- hints.push({
246
- type: 'demo',
247
- link: demo.link,
248
- priority: Object.values(_objectSpread(_objectSpread({}, matchMapping), titleMatchMapping)).reduce(function (acc, p) {
249
- return acc + p;
250
- }, 0),
251
- highlightTitleTexts: highlightTitleTexts,
252
- highlightTexts: highlightTexts
253
- });
254
- }
255
- }); // find page hints
256
-
257
- if (matchReg.test(data.title)) {
258
- var _data$sections$;
259
-
260
- var _generateHighlightTex11 = generateHighlightTexts(data.title, keywords, 100),
261
- _generateHighlightTex12 = _slicedToArray(_generateHighlightTex11, 2),
262
- highlightTitleTexts = _generateHighlightTex12[0],
263
- titleMatchMapping = _generateHighlightTex12[1];
264
-
265
- hints.push({
266
- type: 'page',
267
- link: data.link,
268
- priority: Object.values(titleMatchMapping).reduce(function (acc, p) {
269
- return acc + p;
270
- }, 0),
271
- highlightTitleTexts: highlightTitleTexts,
272
- highlightTexts: generateHighlightTexts(((_data$sections$ = data.sections[0]) === null || _data$sections$ === void 0 ? void 0 : _data$sections$.paragraphs[0]) || '', keywords)[0]
273
- });
274
- } // create nav result if there has any hint
275
-
276
-
277
- if (hints.length) {
278
- var _resultMapping$key, _resultMapping$key$hi;
279
-
280
- var key = data.navTitle || '$ROOT';
281
- (_resultMapping$key = resultMapping[key]) !== null && _resultMapping$key !== void 0 ? _resultMapping$key : resultMapping[key] = {
282
- title: data.navTitle,
283
- priority: data.navOrder * 1000,
284
- hints: []
285
- };
286
-
287
- (_resultMapping$key$hi = resultMapping[key].hints).push.apply(_resultMapping$key$hi, hints);
288
- }
289
- }); // sort hints
290
-
291
- Object.values(resultMapping).forEach(function (_ref3) {
292
- var hints = _ref3.hints;
293
- hints.sort(function (prev, next) {
294
- return next.priority - prev.priority;
295
- });
296
- });
297
- return Object.values(resultMapping).sort(function (prev, next) {
298
- return next.priority - prev.priority;
299
- });
300
- }
301
-
302
- var metadata;
303
-
304
- self.onmessage = function (_ref4) {
305
- var data = _ref4.data;
306
-
307
- switch (data.action) {
308
- case 'generate-metadata':
309
- metadata = generateSearchMetadata(data.args.routes, data.args.demos, data.args.nav);
310
- break;
311
-
312
- case 'get-search-result':
313
- self.postMessage(generateSearchResult(metadata, data.args.keywords));
314
- break;
315
-
316
- default:
317
- }
318
- };