UNPKG

@sanity/desk-tool

Version:

Tool for managing all sorts of content in a structured manner

348 lines (336 loc) • 17.1 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createResolvedPaneNodeStream = createResolvedPaneNodeStream; var _isEqual2 = _interopRequireDefault(require("lodash/isEqual")); var _rxjs = require("rxjs"); var _operators = require("rxjs/operators"); var _generateHelpUrl = require("@sanity/generate-help-url"); var _defaultStructure = require("../defaultStructure"); var _assignId = require("./assignId"); var _createPaneResolver = require("./createPaneResolver"); var _memoBind = require("./memoBind"); var _PaneResolutionError = require("./PaneResolutionError"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } 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; } } }; } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } 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; } } 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; } 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; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); } 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); } function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest(); } 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."); } 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); } 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; } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } /** * the fallback editor child that is implicitly inserted into the structure tree * if the id starts with `__edit__` */ var fallbackEditorChild = (nodeId, context) => { var id = nodeId.replace(/^__edit__/, ''); var params = context.params, payload = context.payload; var type = params.type, template = params.template; if (!type) { throw new Error("Document type for document with ID ".concat(id, " was not provided in the router params.")); } var defaultDocumentBuilder = (0, _defaultStructure.defaultDocument)({ schemaType: type, documentId: id }); defaultDocumentBuilder = defaultDocumentBuilder.id('editor').title('Editor'); if (template) { defaultDocumentBuilder = defaultDocumentBuilder.initialValueTemplate(template, payload); } return defaultDocumentBuilder.serialize(); }; /** * takes in a `RouterPaneSiblingContext` and returns a normalized string * representation that can be used for comparisons */ function hashContext(context) { var _context$serializeOpt, _context$serializeOpt2; return "contextHash(".concat(JSON.stringify({ id: context.id, parentId: parent && (0, _assignId.assignId)(parent), path: context.path, index: context.index, splitIndex: context.splitIndex, serializeOptionsIndex: (_context$serializeOpt = context.serializeOptions) === null || _context$serializeOpt === void 0 ? void 0 : _context$serializeOpt.index, serializeOptionsPath: (_context$serializeOpt2 = context.serializeOptions) === null || _context$serializeOpt2 === void 0 ? void 0 : _context$serializeOpt2.path }), ")"); } /** * takes in `ResolvedPaneMeta` and returns a normalized string representation * that can be used for comparisons */ var hashResolvedPaneMeta = meta => { var normalized = { type: meta.type, id: meta.routerPaneSibling.id, params: meta.routerPaneSibling.params || {}, payload: meta.routerPaneSibling.payload || null, flatIndex: meta.flatIndex, groupIndex: meta.groupIndex, siblingIndex: meta.siblingIndex, path: meta.path, paneNode: meta.type === 'resolvedMeta' ? (0, _assignId.assignId)(meta.paneNode) : null }; return "metaHash(".concat(JSON.stringify(normalized), ")"); }; /** * Represents one flattened "router pane", including the source group and * sibling indexes. * * @see RouterPanes */ /** * The state of the accumulator used to store and manage memo cache state */ /** * The result of pane resolving */ /** * A recursive pane resolving function. Starts at one unresolved pane node and * continues until there is no more flattened router panes that can be used as * input to the unresolved panes. */ function resolvePaneTree(_ref) { var unresolvedPane = _ref.unresolvedPane, flattenedRouterPanes = _ref.flattenedRouterPanes, parent = _ref.parent, path = _ref.path, resolvePane = _ref.resolvePane; var _flattenedRouterPanes = _toArray(flattenedRouterPanes), current = _flattenedRouterPanes[0], rest = _flattenedRouterPanes.slice(1); var next = rest[0]; var context = { id: current.routerPaneSibling.id, splitIndex: current.siblingIndex, parent, path: [...path, current.routerPaneSibling.id], index: current.flatIndex, params: current.routerPaneSibling.params || {}, payload: current.routerPaneSibling.payload }; try { return resolvePane(unresolvedPane, context, current.flatIndex).pipe( // this switch map receives a resolved pane (0, _operators.switchMap)(paneNode => { // we can create a `resolvedMeta` type using it var resolvedPaneMeta = _objectSpread(_objectSpread({ type: 'resolvedMeta' }, current), {}, { paneNode: paneNode, path: context.path }); // for the other unresolved panes, we can create "loading panes" var loadingPanes = rest.map((i, restIndex) => { var loadingPanePath = [...context.path, ...rest.slice(restIndex).map((_, currentIndex) => "[".concat(i.flatIndex + currentIndex, "]"))]; var loadingPane = _objectSpread({ type: 'loading', path: loadingPanePath, paneNode: null }, i); return loadingPane; }); if (!rest.length) { return (0, _rxjs.of)([resolvedPaneMeta]); } var nextStream; if ( // the fallback editor case next !== null && next !== void 0 && next.routerPaneSibling.id.startsWith('__edit__')) { nextStream = resolvePaneTree({ unresolvedPane: fallbackEditorChild, flattenedRouterPanes: rest, parent, path: context.path, resolvePane }); } else if (current.groupIndex === (next === null || next === void 0 ? void 0 : next.groupIndex)) { // if the next flattened router pane has the same group index as the // current flattened router pane, then the next flattened router pane // belongs to the same group (i.e. it is a split pane) nextStream = resolvePaneTree({ unresolvedPane, flattenedRouterPanes: rest, parent, path, resolvePane }); } else { // normal children resolving nextStream = resolvePaneTree({ unresolvedPane: typeof paneNode.child === 'function' ? (0, _memoBind.memoBind)(paneNode, 'child') : paneNode.child, flattenedRouterPanes: rest, parent: paneNode, path: context.path, resolvePane }); } return (0, _rxjs.concat)( // we emit the loading panes first in a concat (this emits immediately) (0, _rxjs.of)([resolvedPaneMeta, ...loadingPanes]), // then whenever the next stream is done, the results will be combined. nextStream.pipe((0, _operators.map)(nextResolvedPanes => [resolvedPaneMeta, ...nextResolvedPanes]))); })); } catch (e) { if (e instanceof _PaneResolutionError.PaneResolutionError) { if (e.context) { console.warn("Pane resolution error at index ".concat(e.context.index).concat(e.context.splitIndex > 0 ? " for split pane index ".concat(e.context.splitIndex) : '', ": ").concat(e.message).concat(e.helpId ? " - see ".concat((0, _generateHelpUrl.generateHelpUrl)(e.helpId)) : ''), e); } if (e.helpId === 'structure-item-returned-no-child') { // returning an observable of an empty array will remove loading panes // note: this one intentionally does not throw return (0, _rxjs.of)([]); } } throw e; } } /** * Takes in a stream of `RouterPanes` and an unresolved root pane and returns * a stream of `ResolvedPaneMeta` */ function createResolvedPaneNodeStream(_ref2) { var routerPanesStream = _ref2.routerPanesStream, rootPaneNode = _ref2.rootPaneNode, _ref2$initialCacheSta = _ref2.initialCacheState, initialCacheState = _ref2$initialCacheSta === void 0 ? { cacheKeysByFlatIndex: [], flattenedRouterPanes: [], resolvedPaneCache: new Map(), resolvePane: () => _rxjs.NEVER } : _ref2$initialCacheSta; var resolvedPanes$ = routerPanesStream.pipe( // add in implicit "root" router pane (0, _operators.map)(rawRouterPanes => [[{ id: 'root' }], ...rawRouterPanes]), // create flattened router panes (0, _operators.map)(routerPanes => { var flattenedRouterPanes = routerPanes.flatMap((routerPaneGroup, groupIndex) => routerPaneGroup.map((routerPaneSibling, siblingIndex) => ({ routerPaneSibling, groupIndex, siblingIndex }))) // add in the flat index .map((i, index) => _objectSpread(_objectSpread({}, i), {}, { flatIndex: index })); return flattenedRouterPanes; }), // calculate a "diffIndex" used for clearing the memo cache (0, _operators.startWith)([]), (0, _operators.pairwise)(), (0, _operators.map)(_ref3 => { var _ref4 = _slicedToArray(_ref3, 2), prev = _ref4[0], curr = _ref4[1]; for (var i = 0; i < curr.length; i++) { var prevValue = prev[i]; var currValue = curr[i]; if (!(0, _isEqual2.default)(prevValue, currValue)) { return { flattenedRouterPanes: curr, diffIndex: i }; } } return { flattenedRouterPanes: curr, diffIndex: curr.length }; }), // create the memoized `resolvePane` function and manage the memo cache (0, _operators.scan)((acc, next) => { var cacheKeysByFlatIndex = acc.cacheKeysByFlatIndex, resolvedPaneCache = acc.resolvedPaneCache; var flattenedRouterPanes = next.flattenedRouterPanes, diffIndex = next.diffIndex; // use the `cacheKeysByFlatIndex` like a dictionary to find cache keys to // and cache keys to delete var beforeDiffIndex = cacheKeysByFlatIndex.slice(0, diffIndex + 1); var afterDiffIndex = cacheKeysByFlatIndex.slice(diffIndex + 1); var keysToKeep = new Set(beforeDiffIndex.flatMap(keySet => Array.from(keySet))); var keysToDelete = afterDiffIndex.flatMap(keySet => Array.from(keySet)).filter(key => !keysToKeep.has(key)); var _iterator = _createForOfIteratorHelper(keysToDelete), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var _key = _step.value; resolvedPaneCache.delete(_key); } // create a memoizing pane resolver middleware that utilizes the cache // maintained above. this keeps the cache from growing indefinitely } catch (err) { _iterator.e(err); } finally { _iterator.f(); } var memoize = nextFn => (unresolvedPane, context, flatIndex) => { var key = unresolvedPane && "".concat((0, _assignId.assignId)(unresolvedPane), "-").concat(hashContext(context)); var cachedResolvedPane = key && resolvedPaneCache.get(key); if (cachedResolvedPane) return cachedResolvedPane; var result = nextFn(unresolvedPane, context, flatIndex); if (!key) return result; var cacheKeySet = cacheKeysByFlatIndex[flatIndex] || new Set(); cacheKeySet.add(key); cacheKeysByFlatIndex[flatIndex] = cacheKeySet; resolvedPaneCache.set(key, result); return result; }; return { flattenedRouterPanes, cacheKeysByFlatIndex, resolvedPaneCache, resolvePane: (0, _createPaneResolver.createPaneResolver)(memoize) }; }, initialCacheState), // run the memoized, recursive resolving (0, _operators.switchMap)(_ref5 => { var flattenedRouterPanes = _ref5.flattenedRouterPanes, resolvePane = _ref5.resolvePane; return resolvePaneTree({ unresolvedPane: rootPaneNode, flattenedRouterPanes, parent: null, path: [], resolvePane }); })); // after we've created a stream of `ResolvedPaneMeta[]`, we need to clean up // the results to remove unwanted loading panes and prevent unnecessary // emissions return resolvedPanes$.pipe( // this diffs the previous emission with the current one. if there is a new // loading pane at the same position where a previous pane already had a // resolved value (looking at the IDs to compare), then return the previous // pane instead of the loading pane (0, _operators.scan)((prev, next) => next.map((nextPane, index) => { var prevPane = prev[index]; if (!prevPane) return nextPane; if (nextPane.type !== 'loading') return nextPane; if (prevPane.routerPaneSibling.id === nextPane.routerPaneSibling.id) { return prevPane; } return nextPane; }), []), // this prevents duplicate emissions (0, _operators.distinctUntilChanged)((prev, next) => { if (prev.length !== next.length) return false; for (var i = 0; i < next.length; i++) { var prevValue = prev[i]; var nextValue = next[i]; if (hashResolvedPaneMeta(prevValue) !== hashResolvedPaneMeta(nextValue)) { return false; } } return true; })); }