UNPKG

@sanity/form-builder

Version:
150 lines (147 loc) • 8.43 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getReferenceInfo = getReferenceInfo; exports.search = search; var _operators = require("rxjs/operators"); var _rxjs = require("rxjs"); var _internal = require("@sanity/base/_internal"); var _versionedClient = require("../../versionedClient"); function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _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 _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 _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } // eslint-disable-next-line camelcase var READABLE = { available: true, reason: _internal.AvailabilityReason.READABLE }; var PERMISSION_DENIED = { available: false, reason: _internal.AvailabilityReason.PERMISSION_DENIED }; var NOT_FOUND = { available: false, reason: _internal.AvailabilityReason.NOT_FOUND }; /** * Takes an id and a reference schema type, returns metadata about it * @param id * @param referenceType */ function getReferenceInfo(id, referenceType) { var _getIdPair = (0, _internal.getIdPair)(id), publishedId = _getIdPair.publishedId, draftId = _getIdPair.draftId; return (0, _internal.unstable_observeDocumentPairAvailability)(id).pipe((0, _operators.switchMap)(_ref => { var draftAvailability = _ref.draft, publishedAvailability = _ref.published; if (!draftAvailability.available && !publishedAvailability.available) { // combine availability of draft + published var availability = draftAvailability.reason === 'PERMISSION_DENIED' || publishedAvailability.reason === 'PERMISSION_DENIED' ? PERMISSION_DENIED : NOT_FOUND; // short circuit, neither draft nor published is available so no point in trying to get preview return (0, _rxjs.of)({ id, type: undefined, availability, preview: { draft: undefined, published: undefined } }); } return (0, _rxjs.combineLatest)([(0, _internal.observeDocumentTypeFromId)(draftId), (0, _internal.observeDocumentTypeFromId)(publishedId)]).pipe((0, _operators.switchMap)(_ref2 => { var _ref3 = _slicedToArray(_ref2, 2), draftTypeName = _ref3[0], publishedTypeName = _ref3[1]; // assume draft + published are always same type var typeName = draftTypeName || publishedTypeName; if (!typeName) { // we have already asserted that either the draft or the published document is readable, so // if we get here we can't read the _type, so we're likely to be in an inconsistent state // waiting for an update to reach the client. Since we're in the context of a reactive stream based on // the _type we'll get it eventually return _rxjs.EMPTY; } // get schema type for the referenced document var refSchemaType = referenceType.to.find(memberType => memberType.name === typeName); var previewPaths = [...((0, _internal.getPreviewPaths)(refSchemaType.preview) || []), ['_updatedAt'], ['_createdAt']]; var draftPreview$ = (0, _internal.observePaths)(draftId, previewPaths).pipe((0, _operators.map)(result => result ? (0, _internal.prepareForPreview)(result, refSchemaType) : result)); var publishedPreview$ = (0, _internal.observePaths)(publishedId, previewPaths).pipe((0, _operators.map)(result => result ? (0, _internal.prepareForPreview)(result, refSchemaType) : result)); return (0, _rxjs.combineLatest)([draftPreview$, publishedPreview$]).pipe((0, _operators.map)(_ref4 => { var _ref5 = _slicedToArray(_ref4, 2), draftPreview = _ref5[0], publishedPreview = _ref5[1]; var availability = // eslint-disable-next-line no-nested-ternary draftAvailability.available || publishedAvailability.available ? READABLE : draftAvailability.reason === 'PERMISSION_DENIED' || publishedAvailability.reason === 'PERMISSION_DENIED' ? PERMISSION_DENIED : NOT_FOUND; return { type: typeName, id: publishedId, availability, preview: { draft: draftPreview, published: publishedPreview } }; })); })); })); } /** * when we get a search result it may not include all [draft, published] id pairs for documents matching the * query. For example: searching for "potato" may yield a hit in the draft, but not the published (or vice versa) * This method takes a list of collated search hits and returns an array of the missing "counterpart" ids * @param collatedHits */ function getCounterpartIds(collatedHits) { return collatedHits.filter(collatedHit => // we're interested in hits where either draft or published is missing !collatedHit.draft || !collatedHit.published).map(collatedHit => // if we have the draft, return the published id or vice versa collatedHit.draft ? collatedHit.id : (0, _internal.getDraftId)(collatedHit.id)); } function getExistingCounterparts(ids) { return ids.length === 0 ? (0, _rxjs.of)([]) : _versionedClient.searchClient.observable.fetch("*[_id in $ids]._id", { ids }, { tag: 'get-counterpart-ids' }); } function search(textTerm, type, options) { var searchWeighted = (0, _internal.createWeightedSearch)(type.to, _versionedClient.searchClient, options); return searchWeighted(textTerm, { includeDrafts: true }).pipe((0, _operators.map)(results => results.map(result => result.hit)), (0, _operators.map)(_internal.collate), // pick the 100 best matches (0, _operators.map)(collated => collated.slice(0, 100)), (0, _operators.mergeMap)(collated => { // Note: It might seem like this step is redundant, but it's here for a reason: // The list of search hits returned from here will be passed as options to the reference input's autocomplete. When // one of them gets selected by the user, it will then be passed as the argument to the `onChange` handler in the // Reference Input. This handler will then look at the passed value to determine whether to make a link to a // draft (using _strengthenOnPublish) or a published document. // // Without this step, in a case where both a draft and a published version exist but only the draft matches // the search term, we'd end up making a reference with `_strengthenOnPublish: true`, when we instead should be // making a normal reference to the published id return getExistingCounterparts(getCounterpartIds(collated)).pipe((0, _operators.map)(existingCounterpartIds => { return collated.map(entry => { var draftId = (0, _internal.getDraftId)(entry.id); return { id: entry.id, type: entry.type, draft: entry.draft || existingCounterpartIds.includes(draftId) ? { _id: draftId, _type: entry.type } : undefined, published: entry.published || existingCounterpartIds.includes(entry.id) ? { _id: entry.id, _type: entry.type } : undefined }; }); })); })); }