@jpmorganchase/mosaic-plugins 0.1.0-beta.8 → 0.1.0-beta.81

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 (80) hide show
  1. package/dist/$AliasPlugin.d.ts +10 -0
  2. package/dist/$AliasPlugin.js +49 -228
  3. package/dist/$AliasPlugin.js.map +1 -1
  4. package/dist/$CodeModPlugin.d.ts +7 -0
  5. package/dist/$CodeModPlugin.js +18 -118
  6. package/dist/$CodeModPlugin.js.map +1 -1
  7. package/dist/$RefPlugin.d.ts +31 -0
  8. package/dist/$RefPlugin.js +123 -451
  9. package/dist/$RefPlugin.js.map +1 -1
  10. package/dist/$TagPlugin.d.ts +28 -0
  11. package/dist/$TagPlugin.js +51 -234
  12. package/dist/$TagPlugin.js.map +1 -1
  13. package/dist/BreadcrumbsPlugin.d.ts +19 -0
  14. package/dist/BreadcrumbsPlugin.js +87 -112
  15. package/dist/BreadcrumbsPlugin.js.map +1 -1
  16. package/dist/BrokenLinksPlugin.d.ts +10 -0
  17. package/dist/BrokenLinksPlugin.js +80 -0
  18. package/dist/BrokenLinksPlugin.js.map +1 -0
  19. package/dist/FragmentPlugin.d.ts +3 -0
  20. package/dist/FragmentPlugin.js +61 -0
  21. package/dist/FragmentPlugin.js.map +1 -0
  22. package/dist/LazyPagePlugin.d.ts +14 -0
  23. package/dist/LazyPagePlugin.js +50 -254
  24. package/dist/LazyPagePlugin.js.map +1 -1
  25. package/dist/PagesWithoutFileExtPlugin.d.ts +9 -0
  26. package/dist/PagesWithoutFileExtPlugin.js +20 -118
  27. package/dist/PagesWithoutFileExtPlugin.js.map +1 -1
  28. package/dist/PropsTablePlugin.d.ts +6 -0
  29. package/dist/PropsTablePlugin.js +88 -0
  30. package/dist/PropsTablePlugin.js.map +1 -0
  31. package/dist/PublicAssetsPlugin.d.ts +18 -0
  32. package/dist/PublicAssetsPlugin.js +28 -0
  33. package/dist/PublicAssetsPlugin.js.map +1 -0
  34. package/dist/ReadingTimePlugin.d.ts +10 -0
  35. package/dist/ReadingTimePlugin.js +39 -0
  36. package/dist/ReadingTimePlugin.js.map +1 -0
  37. package/dist/SearchIndexPlugin.d.ts +56 -0
  38. package/dist/SearchIndexPlugin.js +154 -0
  39. package/dist/SearchIndexPlugin.js.map +1 -0
  40. package/dist/SharedConfigPlugin.d.ts +14 -0
  41. package/dist/SharedConfigPlugin.js +129 -168
  42. package/dist/SharedConfigPlugin.js.map +1 -1
  43. package/dist/SidebarPlugin.d.ts +45 -0
  44. package/dist/SidebarPlugin.js +285 -324
  45. package/dist/SidebarPlugin.js.map +1 -1
  46. package/dist/SiteMapPlugin.d.ts +9 -0
  47. package/dist/SiteMapPlugin.js +23 -91
  48. package/dist/SiteMapPlugin.js.map +1 -1
  49. package/dist/TableOfContentsPlugin.d.ts +20 -0
  50. package/dist/TableOfContentsPlugin.js +44 -0
  51. package/dist/TableOfContentsPlugin.js.map +1 -0
  52. package/dist/utils/PluginError.d.ts +7 -0
  53. package/dist/utils/PluginError.js +13 -0
  54. package/dist/utils/PluginError.js.map +1 -0
  55. package/dist/utils/createPageTest.d.ts +1 -0
  56. package/dist/utils/createPageTest.js +8 -0
  57. package/dist/utils/createPageTest.js.map +1 -0
  58. package/dist/utils/mergePageContent.d.ts +16 -0
  59. package/dist/utils/mergePageContent.js +23 -0
  60. package/dist/utils/mergePageContent.js.map +1 -0
  61. package/dist/utils/normaliseRefs.d.ts +1 -0
  62. package/dist/utils/normaliseRefs.js +56 -275
  63. package/dist/utils/normaliseRefs.js.map +1 -1
  64. package/dist/utils/sortSidebarData.d.ts +29 -0
  65. package/dist/utils/sortSidebarData.js +47 -0
  66. package/dist/utils/sortSidebarData.js.map +1 -0
  67. package/package.json +41 -19
  68. package/CHANGELOG.md +0 -93
  69. package/dist/LocalFolderSavePlugin.js +0 -165
  70. package/dist/LocalFolderSavePlugin.js.map +0 -1
  71. package/dist/NextPrevPagePlugin.js +0 -173
  72. package/dist/NextPrevPagePlugin.js.map +0 -1
  73. package/dist/ReadingTimePlugin.mjs +0 -119
  74. package/dist/ReadingTimePlugin.mjs.map +0 -1
  75. package/dist/SearchIndexPlugin.mjs +0 -268
  76. package/dist/SearchIndexPlugin.mjs.map +0 -1
  77. package/dist/TableOfContentsPlugin.mjs +0 -131
  78. package/dist/TableOfContentsPlugin.mjs.map +0 -1
  79. package/dist/__tests__/BreadcrumbsPlugin.test.js +0 -160
  80. package/dist/__tests__/BreadcrumbsPlugin.test.js.map +0 -1
@@ -1,341 +1,302 @@
1
- function _arrayLikeToArray(arr, len) {
2
- if (len == null || len > arr.length) len = arr.length;
3
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
4
- return arr2;
5
- }
6
- function _arrayWithoutHoles(arr) {
7
- if (Array.isArray(arr)) return _arrayLikeToArray(arr);
8
- }
9
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
10
- try {
11
- var info = gen[key](arg);
12
- var value = info.value;
13
- } catch (error) {
14
- reject(error);
15
- return;
16
- }
17
- if (info.done) {
18
- resolve(value);
19
- } else {
20
- Promise.resolve(value).then(_next, _throw);
21
- }
22
- }
23
- function _asyncToGenerator(fn) {
24
- return function() {
25
- var self = this, args = arguments;
26
- return new Promise(function(resolve, reject) {
27
- var gen = fn.apply(self, args);
28
- function _next(value) {
29
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
30
- }
31
- function _throw(err) {
32
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
33
- }
34
- _next(undefined);
35
- });
36
- };
37
- }
38
- function _iterableToArray(iter) {
39
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
40
- }
41
- function _nonIterableSpread() {
42
- throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
43
- }
44
- function _toConsumableArray(arr) {
45
- return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
46
- }
47
- function _unsupportedIterableToArray(o, minLen) {
48
- if (!o) return;
49
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
50
- var n = Object.prototype.toString.call(o).slice(8, -1);
51
- if (n === "Object" && o.constructor) n = o.constructor.name;
52
- if (n === "Map" || n === "Set") return Array.from(n);
53
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
54
- }
55
- import regeneratorRuntime from "regenerator-runtime";
56
- import path from "path";
1
+ import path from 'path';
2
+ import { sidebarSortConfigSchema } from '@jpmorganchase/mosaic-schemas';
3
+ import { cloneDeep, escapeRegExp } from 'lodash-es';
4
+ import { isDataNode, isGroupNode, sortSidebarData } from './utils/sortSidebarData.js';
57
5
  function createFileGlob(patterns, pageExtensions) {
58
6
  if (Array.isArray(patterns)) {
59
- return patterns.map(function(pattern) {
60
- return createFileGlob(pattern, pageExtensions);
61
- });
7
+ return patterns.map(pattern => createFileGlob(pattern, pageExtensions));
62
8
  }
63
9
  if (pageExtensions.length === 1) {
64
- return "".concat(patterns).concat(pageExtensions[0]);
10
+ return `${patterns}${pageExtensions[0]}`;
65
11
  }
66
- return "".concat(patterns, "{").concat(pageExtensions.join(","), "}");
12
+ return `${patterns}{${pageExtensions.join(',')}}`;
67
13
  }
68
- function isSubfolderIndex(page, dirName) {
69
- return page.fullPath.split("/").length === String(dirName).split("/").length + 2;
14
+ function getPageLevel(page) {
15
+ return page.route.split('/').length - 2;
70
16
  }
71
- function sortFn(pageA, pageB, dirName) {
72
- // Always pin /index to the front
73
- var route = "".concat(dirName, "/index");
74
- if (pageA.route === route) {
75
- return -1;
76
- }
77
- if (pageB.route === route) {
78
- return 1;
79
- }
80
- return (pageB.sidebar && pageB.sidebar.priority ? pageB.sidebar.priority : -1) - (pageA.sidebar && pageA.sidebar.priority ? pageA.sidebar.priority : -1);
17
+ function sortByPathLevel(pathA, pathB) {
18
+ const pathALevel = pathA.split('/').length;
19
+ const pathBLevel = pathB.split('/').length;
20
+ return pathBLevel - pathALevel;
81
21
  }
82
- function filterFn(page) {
83
- return !(page.sidebar && page.sidebar.exclude);
22
+ /**
23
+ * Given the sharedSortConfig
24
+ * 1. find the field specified by 'field' in the sort config
25
+ * 2. transform the field value into the type specified by 'dataType'
26
+ * @param page
27
+ * @param sharedSortConfig
28
+ * @returns transformed field value
29
+ */
30
+ function getSortFieldData(page, sharedSortConfig) {
31
+ let fieldData;
32
+ if (sharedSortConfig !== undefined) {
33
+ const { field, dataType = 'string' } = sharedSortConfig;
34
+ field
35
+ .replace(/^(?:\.\.\/|\.\/)+/, '')
36
+ .split('/')
37
+ .forEach(part => {
38
+ const source = fieldData === undefined ? page : fieldData;
39
+ if (Object.prototype.hasOwnProperty.call(source, part)) {
40
+ fieldData = source[part];
41
+ }
42
+ });
43
+ switch (dataType) {
44
+ case 'date':
45
+ fieldData = new Date(fieldData).getTime(); // call getTime to convert to a number
46
+ break;
47
+ case 'string':
48
+ fieldData = String(fieldData);
49
+ break;
50
+ case 'number':
51
+ fieldData = Number(fieldData);
52
+ break;
53
+ default:
54
+ fieldData = String(fieldData);
55
+ }
56
+ }
57
+ return fieldData;
84
58
  }
59
+ const createPageTest = (ignorePages, pageExtensions) => {
60
+ const extTest = new RegExp(`${pageExtensions.map(ext => escapeRegExp(ext)).join('|')}$`);
61
+ const ignoreTest = new RegExp(`${ignorePages.map(ignore => escapeRegExp(ignore)).join('|')}$`);
62
+ return file => !ignoreTest.test(file) && extTest.test(file) && !path.basename(file).startsWith('.');
63
+ };
64
+ /**
65
+ * Directories create groups of pages, the index file within that group is assigned GROUP_DEFAULT_PRIORITY
66
+ * to ensure it comes first. This can be overriden by the metadata to move the position of the default page.
67
+ */
68
+ const GROUP_DEFAULT_PRIORITY = 999;
85
69
  /**
86
- * Sorts the pages in a folder by priority and then exports a JSON file (name: `options.filename`) with the
70
+ * Sorts the pages in a folder by priority and then exports a JSON file with the
87
71
  * sidebar tree from that directory downwards and adds sidebar data into frontmatter for each page.
88
- */ var SidebarPlugin = {
89
- $beforeSend: function $beforeSend(mutableFilesystem, param, options) {
90
- var config = param.config, serialiser = param.serialiser, ignorePages = param.ignorePages, pageExtensions = param.pageExtensions;
91
- return _asyncToGenerator(/*#__PURE__*/ regeneratorRuntime.mark(function _callee() {
92
- var setPageRefs, setChildPageRefs, _setChildPageRefs, addSidebarDataToFrontmatter, dirs, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, dirName, sidebarFilePath, pages, i;
93
- return regeneratorRuntime.wrap(function _callee$(_ctx) {
94
- while(1)switch(_ctx.prev = _ctx.next){
95
- case 0:
96
- setPageRefs = function _setPageRefs(sidebarFilePath, page, i) {
97
- config.setRef(sidebarFilePath, [
98
- "pages",
99
- "".concat(i),
100
- "id",
101
- "$ref"
102
- ], "".concat(page.fullPath, "#/route"));
103
- var label = page.sidebar && page.sidebar.label ? "".concat(page.fullPath, "#/sidebar/label") : "".concat(page.fullPath, "#/title");
104
- config.setRef(sidebarFilePath, [
105
- "pages",
106
- "".concat(i),
107
- "name",
108
- "$ref"
109
- ], label);
110
- config.setRef(sidebarFilePath, [
111
- "pages",
112
- "".concat(i),
113
- "data",
114
- "link",
115
- "$ref"
116
- ], "".concat(page.fullPath, "#/route"));
117
- };
118
- setChildPageRefs = function _setChildPageRefs1(page, dirName, i, sidebarFilePath) {
119
- return _setChildPageRefs.apply(this, arguments);
120
- };
121
- _setChildPageRefs = function __setChildPageRefs() {
122
- _setChildPageRefs = _asyncToGenerator(/*#__PURE__*/ regeneratorRuntime.mark(function _callee(page, dirName, i, sidebarFilePath) {
123
- var childDirName, childNodeSidebarPath, childPages, j;
124
- return regeneratorRuntime.wrap(function _callee$(_ctx) {
125
- while(1)switch(_ctx.prev = _ctx.next){
126
- case 0:
127
- if (!isSubfolderIndex(page, dirName)) {
128
- _ctx.next = 11;
129
- break;
130
- }
131
- childDirName = path.posix.dirname(page.fullPath);
132
- childNodeSidebarPath = path.posix.join(childDirName, options.filename);
133
- _ctx.t0 = Promise;
134
- _ctx.next = 6;
135
- return mutableFilesystem.promises.glob(createFileGlob([
136
- "*",
137
- "*/index"
138
- ], pageExtensions), {
139
- onlyFiles: true,
140
- cwd: String(childDirName),
141
- ignore: ignorePages.map(function(ignore) {
142
- return "**/".concat(ignore);
143
- })
144
- });
145
- case 6:
146
- _ctx.t1 = _ctx.sent.map(function() {
147
- var _ref = _asyncToGenerator(/*#__PURE__*/ regeneratorRuntime.mark(function _callee(pagePath) {
148
- var deserialisedPage;
149
- return regeneratorRuntime.wrap(function _callee$(_ctx) {
150
- while(1)switch(_ctx.prev = _ctx.next){
151
- case 0:
152
- _ctx.t0 = serialiser;
153
- _ctx.t1 = pagePath;
154
- _ctx.next = 4;
155
- return mutableFilesystem.promises.readFile(pagePath);
156
- case 4:
157
- _ctx.t2 = _ctx.sent;
158
- _ctx.next = 7;
159
- return _ctx.t0.deserialise.call(_ctx.t0, _ctx.t1, _ctx.t2);
160
- case 7:
161
- deserialisedPage = _ctx.sent;
162
- return _ctx.abrupt("return", deserialisedPage);
163
- case 9:
164
- case "end":
165
- return _ctx.stop();
166
- }
167
- }, _callee);
168
- }));
169
- return function(pagePath) {
170
- return _ref.apply(this, arguments);
171
- };
172
- }());
173
- _ctx.next = 9;
174
- return _ctx.t0.all.call(_ctx.t0, _ctx.t1);
175
- case 9:
176
- childPages = _ctx.sent.filter(function(filterPage) {
177
- return filterFn(filterPage);
178
- });
179
- if (childPages.length > 1) {
180
- for(j = 1; j < childPages.length; j++){
181
- config.setRef(sidebarFilePath, [
182
- "pages",
183
- "".concat(i),
184
- "childNodes",
185
- "".concat(j - 1),
186
- "$ref"
187
- ], "".concat(childNodeSidebarPath, "#/pages/").concat(j));
188
- }
189
- }
190
- case 11:
191
- case "end":
192
- return _ctx.stop();
193
- }
194
- }, _callee);
195
- }));
196
- return _setChildPageRefs.apply(this, arguments);
197
- };
198
- addSidebarDataToFrontmatter = function _addSidebarDataToFrontmatter(page, dirName) {
199
- var _posix;
200
- var dirNameLevels = String(dirName).split("/").filter(function(level) {
201
- return level;
202
- });
203
- var sidebarRootDir = (_posix = path.posix).join.apply(_posix, [
204
- "/"
205
- ].concat(_toConsumableArray(dirNameLevels.slice(0, dirNameLevels.length < 3 ? dirNameLevels.length : 3)), [
206
- "/"
207
- ]));
208
- config.setRef(String(page.fullPath), [
209
- "sidebarData",
210
- "$ref"
211
- ], path.posix.join(String(sidebarRootDir), options.filename, "#", "pages"));
212
- };
213
- ;
214
- ;
215
- ;
216
- ;
217
- _ctx.next = 10;
218
- return mutableFilesystem.promises.glob("**", {
219
- onlyDirectories: true,
220
- cwd: "/"
221
- });
222
- case 10:
223
- dirs = _ctx.sent;
224
- _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
225
- _ctx.prev = 12;
226
- _iterator = dirs[Symbol.iterator]();
227
- case 14:
228
- if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
229
- _ctx.next = 30;
230
- break;
231
- }
232
- dirName = _step.value;
233
- sidebarFilePath = path.posix.join(String(dirName), options.filename);
234
- _ctx.t0 = Promise;
235
- _ctx.next = 20;
236
- return mutableFilesystem.promises.glob(createFileGlob([
237
- "*",
238
- "*/index"
239
- ], pageExtensions), {
240
- onlyFiles: true,
241
- cwd: String(dirName),
242
- ignore: ignorePages.map(function(ignore) {
243
- return "**/".concat(ignore);
244
- })
245
- });
246
- case 20:
247
- _ctx.t1 = _ctx.sent.map(function() {
248
- var _ref = _asyncToGenerator(/*#__PURE__*/ regeneratorRuntime.mark(function _callee(pagePath) {
249
- var deserialisedPage;
250
- return regeneratorRuntime.wrap(function _callee$(_ctx) {
251
- while(1)switch(_ctx.prev = _ctx.next){
252
- case 0:
253
- _ctx.t0 = serialiser;
254
- _ctx.t1 = pagePath;
255
- _ctx.next = 4;
256
- return mutableFilesystem.promises.readFile(pagePath);
257
- case 4:
258
- _ctx.t2 = _ctx.sent;
259
- _ctx.next = 7;
260
- return _ctx.t0.deserialise.call(_ctx.t0, _ctx.t1, _ctx.t2);
261
- case 7:
262
- deserialisedPage = _ctx.sent;
263
- return _ctx.abrupt("return", deserialisedPage);
264
- case 9:
265
- case "end":
266
- return _ctx.stop();
267
- }
268
- }, _callee);
269
- }));
270
- return function(pagePath) {
271
- return _ref.apply(this, arguments);
272
- };
273
- }());
274
- _ctx.next = 23;
275
- return _ctx.t0.all.call(_ctx.t0, _ctx.t1);
276
- case 23:
277
- pages = _ctx.sent.filter(function(page) {
278
- return filterFn(page);
279
- }).sort(function(pageA, pageB) {
280
- return sortFn(pageA, pageB, dirName);
281
- });
282
- for(i = 0; i < pages.length; i++){
283
- setPageRefs(sidebarFilePath, pages[i], i);
284
- setChildPageRefs(pages[i], dirName, i, sidebarFilePath);
285
- addSidebarDataToFrontmatter(pages[i], dirName);
286
- }
287
- _ctx.next = 27;
288
- return mutableFilesystem.promises.writeFile(sidebarFilePath, "[]");
289
- case 27:
290
- _iteratorNormalCompletion = true;
291
- _ctx.next = 14;
292
- break;
293
- case 30:
294
- _ctx.next = 36;
295
- break;
296
- case 32:
297
- _ctx.prev = 32;
298
- _ctx.t2 = _ctx["catch"](12);
299
- _didIteratorError = true;
300
- _iteratorError = _ctx.t2;
301
- case 36:
302
- _ctx.prev = 36;
303
- _ctx.prev = 37;
304
- if (!_iteratorNormalCompletion && _iterator.return != null) {
305
- _iterator.return();
72
+ *
73
+ * Additionally, add to frontmatter
74
+ * navigation -> prev -> { title, route }
75
+ * navigation -> next -> { title, route }
76
+ * to define the previous/next page in the page sequence, as defined by sidebar label and priority
77
+ */
78
+ const SidebarPlugin = {
79
+ async $afterSource(pages, { ignorePages = [], pageExtensions = [] }) {
80
+ for (const page of pages) {
81
+ const isNonHiddenPage = createPageTest(ignorePages, pageExtensions);
82
+ if (!isNonHiddenPage(page.fullPath)) {
83
+ continue;
84
+ }
85
+ let sidebar = {
86
+ label: page.title,
87
+ groupLabel: page?.sidebar?.label || page.title,
88
+ ...page?.sidebar
89
+ };
90
+ page.sidebar = sidebar;
91
+ }
92
+ return pages;
93
+ },
94
+ async $beforeSend(mutableFilesystem, { config, serialiser, ignorePages, pageExtensions }, { filename = 'sidebar.json', rootDirGlob = '*' }) {
95
+ /**
96
+ * Create a list of pages that should be used to build a sidebar.json
97
+ * @param dirName - root path of sidebar
98
+ */
99
+ async function createPageList(rootDir) {
100
+ const isChildOfRootDir = pagePath => {
101
+ const pageDir = path.dirname(pagePath);
102
+ return pageDir.indexOf(rootDir) === 0;
103
+ };
104
+ const pagePaths = (await mutableFilesystem.promises.glob(createFileGlob(['**'], pageExtensions), {
105
+ cwd: String(rootDir),
106
+ ignore: ignorePages.map(ignore => `**/${ignore}`)
107
+ }));
108
+ const filteredPagePaths = pagePaths.filter(isChildOfRootDir);
109
+ const pageList = await Promise.all(filteredPagePaths.map(async (pagePath) => {
110
+ return mutableFilesystem.promises.readFile(pagePath).then(serializedContent => {
111
+ return serialiser.deserialise(pagePath, serializedContent);
112
+ });
113
+ }));
114
+ return pageList;
115
+ }
116
+ /**
117
+ * Group the pages into parent/child hierarchy
118
+ * @param pages - sidebar pages
119
+ */
120
+ function createGroupMap(pages) {
121
+ const sortConfigPages = {};
122
+ return pages.reduce((result, page) => {
123
+ const name = page.sidebar?.label || page.title;
124
+ const sharedSortConfig = page?.sharedConfig?.sidebar?.sort;
125
+ if (sharedSortConfig) {
126
+ try {
127
+ sidebarSortConfigSchema.parse(sharedSortConfig);
128
+ sortConfigPages[`${path.posix.dirname(page.fullPath)}`] = sharedSortConfig;
129
+ }
130
+ catch (e) {
131
+ /**
132
+ * Don't throw a PluginError here as this will stop the sidebar being generated.
133
+ * Plugins need a way to log errors/warnings without exceptions
134
+ */
135
+ console.error(`[Mosaic] SidebarPlugin - Invalid sidebar sort config found in ${page.fullPath}`);
136
+ }
137
+ }
138
+ const priority = page.sidebar?.priority;
139
+ const isGroupDefaultPage = /\/index$/.test(page.route);
140
+ const groupPath = path.posix.dirname(page.fullPath);
141
+ let newChildNode = {
142
+ id: page.route,
143
+ kind: 'data',
144
+ fullPath: page.fullPath,
145
+ name,
146
+ priority: isGroupDefaultPage ? priority || GROUP_DEFAULT_PRIORITY : priority,
147
+ data: { level: getPageLevel(page), link: page.route }
148
+ };
149
+ const currentChildNodes = Object.prototype.hasOwnProperty.call(result, groupPath)
150
+ ? result[groupPath].childNodes
151
+ : [];
152
+ let newGroupNode = {
153
+ ...result[groupPath],
154
+ id: path.posix.dirname(page.route),
155
+ kind: 'group',
156
+ childNodes: [...currentChildNodes, newChildNode]
157
+ };
158
+ if (isGroupDefaultPage) {
159
+ newGroupNode = {
160
+ ...newGroupNode,
161
+ name: page.sidebar?.groupLabel || name,
162
+ priority
163
+ };
164
+ }
165
+ if (!isGroupDefaultPage && sortConfigPages[groupPath] !== undefined) {
166
+ const fieldData = getSortFieldData(page, sortConfigPages[groupPath]);
167
+ newChildNode.sharedSortConfig = {
168
+ ...sortConfigPages[groupPath],
169
+ fieldData
170
+ };
171
+ }
172
+ result[groupPath] = newGroupNode;
173
+ return result;
174
+ }, {});
175
+ }
176
+ /**
177
+ * Link the group map to their parents
178
+ * @param groupMap - unlinked groups of pages
179
+ * @param dirName - root path of sidebar
180
+ */
181
+ function linkGroupMap(groupMap, dirName) {
182
+ const linkedGroupMap = cloneDeep(groupMap);
183
+ const sortedGroupMapKeys = Object.keys(linkedGroupMap).sort(sortByPathLevel);
184
+ sortedGroupMapKeys.forEach(groupPath => {
185
+ let parentGroupPath = path.posix.dirname(groupPath);
186
+ if (linkedGroupMap[parentGroupPath] === undefined) {
187
+ return;
188
+ }
189
+ linkedGroupMap[parentGroupPath].childNodes = [
190
+ ...linkedGroupMap[parentGroupPath].childNodes,
191
+ linkedGroupMap[groupPath]
192
+ ];
193
+ });
194
+ return [linkedGroupMap[dirName]];
195
+ }
196
+ /**
197
+ * Link each page to a sidebar.json file via ref
198
+ * @param pages - sidebar pages
199
+ * @param dirName - root path of sidebar
200
+ */
201
+ function addSidebarDataToFrontmatter(pages, dirName) {
202
+ pages.forEach(page => {
203
+ config.setRef(String(page.fullPath), ['sidebarData', '$ref'], path.posix.join(dirName, filename, '#', 'pages'));
204
+ });
205
+ }
206
+ const createNavigationRefs = (rootDir, currPage, prevPage, nextPage) => {
207
+ if (prevPage) {
208
+ config.setRef(currPage, ['navigation', 'prev', 'title', '$ref'], `${prevPage}#/title`);
209
+ config.setRef(currPage, ['navigation', 'prev', 'route', '$ref'], `${prevPage}#/route`);
210
+ const parentPath = path.posix.dirname(prevPage);
211
+ if (parentPath !== rootDir) {
212
+ config.setRef(currPage, ['navigation', 'prev', 'group', '$ref'], `${parentPath}#/sidebar/groupLabel`);
213
+ }
214
+ }
215
+ if (nextPage) {
216
+ config.setRef(currPage, ['navigation', 'next', 'title', '$ref'], `${nextPage}#/title`);
217
+ config.setRef(currPage, ['navigation', 'next', 'route', '$ref'], `${nextPage}#/route`);
218
+ const parentPath = path.posix.dirname(nextPage);
219
+ if (parentPath !== rootDir) {
220
+ config.setRef(currPage, ['navigation', 'next', 'group', '$ref'], `${parentPath}#/sidebar/groupLabel`);
221
+ }
222
+ }
223
+ };
224
+ function addNavigationToFrontmatter(pages, rootDir) {
225
+ const getRelativeDataNode = (node, position) => {
226
+ let targetNode = node;
227
+ if (isGroupNode(node)) {
228
+ targetNode = node.childNodes[position === 'previous' ? node.childNodes.length - 1 : 0];
229
+ }
230
+ return isGroupNode(targetNode) ? getRelativeDataNode(targetNode, position) : targetNode;
231
+ };
232
+ const isLastPage = page => {
233
+ const lastPage = getRelativeDataNode(pages, 'previous');
234
+ return page === lastPage;
235
+ };
236
+ let prevParentPage = [];
237
+ let nextParentPage = [];
238
+ function recursiveAddNavigation(pages) {
239
+ let nextPage, prevPage;
240
+ pages.forEach((page, pageIndex) => {
241
+ if (isLastPage(page)) {
242
+ nextPage = undefined;
243
+ }
244
+ else if (pageIndex === pages.length - 1) {
245
+ nextPage = nextParentPage.pop();
246
+ }
247
+ else {
248
+ nextPage = getRelativeDataNode(pages[pageIndex + 1], 'next');
249
+ }
250
+ if (pageIndex === 0) {
251
+ prevPage = prevParentPage.pop();
252
+ }
253
+ else {
254
+ prevPage = getRelativeDataNode(pages[pageIndex - 1], 'previous');
255
+ }
256
+ if (isDataNode(page)) {
257
+ createNavigationRefs(rootDir, page.fullPath, prevPage?.fullPath, nextPage?.fullPath);
258
+ }
259
+ else {
260
+ if (nextPage) {
261
+ nextParentPage.push(nextPage);
306
262
  }
307
- case 39:
308
- _ctx.prev = 39;
309
- if (!_didIteratorError) {
310
- _ctx.next = 42;
311
- break;
263
+ if (prevPage) {
264
+ prevParentPage.push(prevPage);
312
265
  }
313
- throw _iteratorError;
314
- case 42:
315
- return _ctx.finish(39);
316
- case 43:
317
- return _ctx.finish(36);
318
- case 44:
319
- case "end":
320
- return _ctx.stop();
321
- }
322
- }, _callee, null, [
323
- [
324
- 12,
325
- 32,
326
- 36,
327
- 44
328
- ],
329
- [
330
- 37,
331
- ,
332
- 39,
333
- 43
334
- ]
335
- ]);
336
- }))();
266
+ recursiveAddNavigation(page.childNodes);
267
+ }
268
+ });
269
+ }
270
+ recursiveAddNavigation(pages);
271
+ }
272
+ const rootUserJourneys = await mutableFilesystem.promises.glob(rootDirGlob, {
273
+ onlyDirectories: true,
274
+ extglob: true,
275
+ cwd: '/'
276
+ });
277
+ const removeExcludedPages = page => !(page.sidebar && page.sidebar.exclude);
278
+ await Promise.all(rootUserJourneys.map(async (rootDir) => {
279
+ const sidebarFilePath = path.posix.join(String(rootDir), filename);
280
+ const pages = await createPageList(rootDir);
281
+ const includedPages = pages.filter(page => removeExcludedPages(page));
282
+ const groupMap = createGroupMap(includedPages);
283
+ const sidebarData = linkGroupMap(groupMap, rootDir);
284
+ if (sidebarData[0] === undefined) {
285
+ console.warn(`[Mosaic] SidebarPlugin - Unable to create a Sidebar grouping for ${rootDir}`);
286
+ console.log('[Mosaic] SidebarPlugin - likely you have a directory without an index file');
287
+ return;
288
+ }
289
+ const sortedRootSidebar = sortSidebarData(sidebarData);
290
+ addNavigationToFrontmatter(sortedRootSidebar, rootDir);
291
+ if (isGroupNode(sortedRootSidebar[0])) {
292
+ await mutableFilesystem.promises.writeFile(sidebarFilePath, JSON.stringify({ pages: sortedRootSidebar[0].childNodes }));
293
+ }
294
+ else {
295
+ console.warn(`[Mosaic] SidebarPlugin - Unable to sort Sidebar grouping for ${rootDir}`);
296
+ }
297
+ addSidebarDataToFrontmatter(pages, rootDir);
298
+ }));
337
299
  }
338
300
  };
339
301
  export default SidebarPlugin;
340
-
341
302
  //# sourceMappingURL=SidebarPlugin.js.map