@sanity/desk-tool
Version:
Tool for managing all sorts of content in a structured manner
75 lines (71 loc) • 2.9 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createPaneResolver = createPaneResolver;
var _rxjs = require("rxjs");
var _operators = require("rxjs/operators");
var _isRecord = require("./isRecord");
var _PaneResolutionError = require("./PaneResolutionError");
var isSubscribable = thing => {
if (!(0, _isRecord.isRecord)(thing)) return false;
return typeof thing.subscribe === 'function' || typeof thing.then === 'function';
};
var isSerializable = thing => {
if (!(0, _isRecord.isRecord)(thing)) return false;
return typeof thing.serialize === 'function';
};
/**
* The signature of the function used to take an `UnresolvedPaneNode` and turn
* it into an `Observable<PaneNode>`.
*/
var rethrowWithPaneResolutionErrors = next => (unresolvedPane, context, flatIndex) => {
try {
return next(unresolvedPane, context, flatIndex);
} catch (e) {
// re-throw errors that are already `PaneResolutionError`s
if (e instanceof _PaneResolutionError.PaneResolutionError) {
throw e;
}
// anything else, wrap with `PaneResolutionError` and set the underlying
// error as a the `cause`
throw new _PaneResolutionError.PaneResolutionError({
message: typeof (e === null || e === void 0 ? void 0 : e.message) === 'string' ? e.message : '',
context,
cause: e
});
}
};
var wrapWithPublishReplay = next => function () {
return next(...arguments).pipe(
// need to add publishReplay + refCount to ensure new subscribers always
// get an emission. without this, memoized observables may get stuck
// waiting for their first emissions resulting in a loading pane
(0, _operators.publishReplay)(1), (0, _operators.refCount)());
};
function createPaneResolver(middleware) {
// note: this API includes a middleware/wrapper function because the function
// is recursive. we want to call the wrapped version of the function always
// (even inside of nested calls) so the identifier invoked for the recursion
// should be the wrapped version
var resolvePane = rethrowWithPaneResolutionErrors(wrapWithPublishReplay(middleware((unresolvedPane, context, flatIndex) => {
if (!unresolvedPane) {
throw new _PaneResolutionError.PaneResolutionError({
message: 'Pane returned no child',
context,
helpId: 'structure-item-returned-no-child'
});
}
if (isSubscribable(unresolvedPane)) {
return (0, _rxjs.from)(unresolvedPane).pipe((0, _operators.switchMap)(result => resolvePane(result, context, flatIndex)));
}
if (isSerializable(unresolvedPane)) {
return resolvePane(unresolvedPane.serialize(context), context, flatIndex);
}
if (typeof unresolvedPane === 'function') {
return resolvePane(unresolvedPane(context.id, context), context, flatIndex);
}
return (0, _rxjs.of)(unresolvedPane);
})));
return resolvePane;
}