@sanity/form-builder
Version:
Sanity form builder
37 lines (36 loc) • 2.4 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = apply;
var DMP = _interopRequireWildcard(require("diff-match-patch"));
function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
var dmp = new DMP.diff_match_patch();
var OPERATIONS = {
replace(currentValue, nextValue) {
return nextValue;
},
set(currentValue, nextValue) {
return nextValue;
},
setIfMissing(currentValue, nextValue) {
return currentValue === undefined ? nextValue : currentValue;
},
unset(currentValue, nextValue) {
return undefined;
},
diffMatchPatch(currentValue, nextValue) {
return dmp.patch_apply(dmp.patch_fromText(nextValue), currentValue)[0];
}
};
var SUPPORTED_PATCH_TYPES = Object.keys(OPERATIONS);
function apply(value, patch) {
if (!SUPPORTED_PATCH_TYPES.includes(patch.type)) {
throw new Error("Received patch of unsupported type: \"".concat(JSON.stringify(patch.type), "\" for string. This is most likely a bug."));
}
if (patch.path.length > 0) {
throw new Error("Cannot apply deep operations on string values. Received patch with type \"".concat(patch.type, "\" and path \"").concat(patch.path.join('.'), " that targeted the value \"").concat(JSON.stringify(value), "\""));
}
return OPERATIONS[patch.type](value, patch.value);
}