slate
Version:
A completely customizable framework for building rich text editors.
1,381 lines (1,331 loc) • 342 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Slate = {}));
})(this, (function (exports) { 'use strict';
// eslint-disable-next-line no-redeclare
var PathRef = {
transform: function transform(ref, op) {
var current = ref.current,
affinity = ref.affinity;
if (current == null) {
return;
}
var path = Path.transform(current, op, {
affinity: affinity
});
ref.current = path;
if (path == null) {
ref.unref();
}
}
};
// eslint-disable-next-line no-redeclare
var PointRef = {
transform: function transform(ref, op) {
var current = ref.current,
affinity = ref.affinity;
if (current == null) {
return;
}
var point = Point.transform(current, op, {
affinity: affinity
});
ref.current = point;
if (point == null) {
ref.unref();
}
}
};
// eslint-disable-next-line no-redeclare
var RangeRef = {
transform: function transform(ref, op) {
var current = ref.current,
affinity = ref.affinity;
if (current == null) {
return;
}
var path = Range.transform(current, op, {
affinity: affinity
});
ref.current = path;
if (path == null) {
ref.unref();
}
}
};
var DIRTY_PATHS = new WeakMap();
var DIRTY_PATH_KEYS = new WeakMap();
var FLUSHING = new WeakMap();
var NORMALIZING = new WeakMap();
var PATH_REFS = new WeakMap();
var POINT_REFS = new WeakMap();
var RANGE_REFS = new WeakMap();
function unwrapExports (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var arrayLikeToArray = createCommonjsModule(function (module) {
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;
}
module.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(arrayLikeToArray);
var arrayWithoutHoles = createCommonjsModule(function (module) {
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return arrayLikeToArray(arr);
}
module.exports = _arrayWithoutHoles, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(arrayWithoutHoles);
var iterableToArray = createCommonjsModule(function (module) {
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
module.exports = _iterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(iterableToArray);
var unsupportedIterableToArray = createCommonjsModule(function (module) {
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);
}
module.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(unsupportedIterableToArray);
var nonIterableSpread = createCommonjsModule(function (module) {
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
module.exports = _nonIterableSpread, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(nonIterableSpread);
var toConsumableArray = createCommonjsModule(function (module) {
function _toConsumableArray(arr) {
return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread();
}
module.exports = _toConsumableArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
var _toConsumableArray = unwrapExports(toConsumableArray);
// eslint-disable-next-line no-redeclare
var Path = {
ancestors: function ancestors(path) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var _options$reverse = options.reverse,
reverse = _options$reverse === void 0 ? false : _options$reverse;
var paths = Path.levels(path, options);
if (reverse) {
paths = paths.slice(1);
} else {
paths = paths.slice(0, -1);
}
return paths;
},
common: function common(path, another) {
var common = [];
for (var i = 0; i < path.length && i < another.length; i++) {
var av = path[i];
var bv = another[i];
if (av !== bv) {
break;
}
common.push(av);
}
return common;
},
compare: function compare(path, another) {
var min = Math.min(path.length, another.length);
for (var i = 0; i < min; i++) {
if (path[i] < another[i]) return -1;
if (path[i] > another[i]) return 1;
}
return 0;
},
endsAfter: function endsAfter(path, another) {
var i = path.length - 1;
var as = path.slice(0, i);
var bs = another.slice(0, i);
var av = path[i];
var bv = another[i];
return Path.equals(as, bs) && av > bv;
},
endsAt: function endsAt(path, another) {
var i = path.length;
var as = path.slice(0, i);
var bs = another.slice(0, i);
return Path.equals(as, bs);
},
endsBefore: function endsBefore(path, another) {
var i = path.length - 1;
var as = path.slice(0, i);
var bs = another.slice(0, i);
var av = path[i];
var bv = another[i];
return Path.equals(as, bs) && av < bv;
},
equals: function equals(path, another) {
return path.length === another.length && path.every(function (n, i) {
return n === another[i];
});
},
hasPrevious: function hasPrevious(path) {
return path[path.length - 1] > 0;
},
isAfter: function isAfter(path, another) {
return Path.compare(path, another) === 1;
},
isAncestor: function isAncestor(path, another) {
return path.length < another.length && Path.compare(path, another) === 0;
},
isBefore: function isBefore(path, another) {
return Path.compare(path, another) === -1;
},
isChild: function isChild(path, another) {
return path.length === another.length + 1 && Path.compare(path, another) === 0;
},
isCommon: function isCommon(path, another) {
return path.length <= another.length && Path.compare(path, another) === 0;
},
isDescendant: function isDescendant(path, another) {
return path.length > another.length && Path.compare(path, another) === 0;
},
isParent: function isParent(path, another) {
return path.length + 1 === another.length && Path.compare(path, another) === 0;
},
isPath: function isPath(value) {
return Array.isArray(value) && (value.length === 0 || typeof value[0] === 'number');
},
isSibling: function isSibling(path, another) {
if (path.length !== another.length) {
return false;
}
var as = path.slice(0, -1);
var bs = another.slice(0, -1);
var al = path[path.length - 1];
var bl = another[another.length - 1];
return al !== bl && Path.equals(as, bs);
},
levels: function levels(path) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var _options$reverse2 = options.reverse,
reverse = _options$reverse2 === void 0 ? false : _options$reverse2;
var list = [];
for (var i = 0; i <= path.length; i++) {
list.push(path.slice(0, i));
}
if (reverse) {
list.reverse();
}
return list;
},
next: function next(path) {
if (path.length === 0) {
throw new Error("Cannot get the next path of a root path [".concat(path, "], because it has no next index."));
}
var last = path[path.length - 1];
return path.slice(0, -1).concat(last + 1);
},
operationCanTransformPath: function operationCanTransformPath(operation) {
switch (operation.type) {
case 'insert_node':
case 'remove_node':
case 'merge_node':
case 'split_node':
case 'move_node':
return true;
default:
return false;
}
},
parent: function parent(path) {
if (path.length === 0) {
throw new Error("Cannot get the parent path of the root path [".concat(path, "]."));
}
return path.slice(0, -1);
},
previous: function previous(path) {
if (path.length === 0) {
throw new Error("Cannot get the previous path of a root path [".concat(path, "], because it has no previous index."));
}
var last = path[path.length - 1];
if (last <= 0) {
throw new Error("Cannot get the previous path of a first child path [".concat(path, "] because it would result in a negative index."));
}
return path.slice(0, -1).concat(last - 1);
},
relative: function relative(path, ancestor) {
if (!Path.isAncestor(ancestor, path) && !Path.equals(path, ancestor)) {
throw new Error("Cannot get the relative path of [".concat(path, "] inside ancestor [").concat(ancestor, "], because it is not above or equal to the path."));
}
return path.slice(ancestor.length);
},
transform: function transform(path, operation) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
if (!path) return null;
// PERF: use destructing instead of immer
var p = _toConsumableArray(path);
var _options$affinity = options.affinity,
affinity = _options$affinity === void 0 ? 'forward' : _options$affinity;
// PERF: Exit early if the operation is guaranteed not to have an effect.
if (path.length === 0) {
return p;
}
switch (operation.type) {
case 'insert_node':
{
var op = operation.path;
if (Path.equals(op, p) || Path.endsBefore(op, p) || Path.isAncestor(op, p)) {
p[op.length - 1] += 1;
}
break;
}
case 'remove_node':
{
var _op = operation.path;
if (Path.equals(_op, p) || Path.isAncestor(_op, p)) {
return null;
} else if (Path.endsBefore(_op, p)) {
p[_op.length - 1] -= 1;
}
break;
}
case 'merge_node':
{
var _op2 = operation.path,
position = operation.position;
if (Path.equals(_op2, p) || Path.endsBefore(_op2, p)) {
p[_op2.length - 1] -= 1;
} else if (Path.isAncestor(_op2, p)) {
p[_op2.length - 1] -= 1;
p[_op2.length] += position;
}
break;
}
case 'split_node':
{
var _op3 = operation.path,
_position = operation.position;
if (Path.equals(_op3, p)) {
if (affinity === 'forward') {
p[p.length - 1] += 1;
} else if (affinity === 'backward') ; else {
return null;
}
} else if (Path.endsBefore(_op3, p)) {
p[_op3.length - 1] += 1;
} else if (Path.isAncestor(_op3, p) && path[_op3.length] >= _position) {
p[_op3.length - 1] += 1;
p[_op3.length] -= _position;
}
break;
}
case 'move_node':
{
var _op4 = operation.path,
onp = operation.newPath;
// If the old and new path are the same, it's a no-op.
if (Path.equals(_op4, onp)) {
return p;
}
if (Path.isAncestor(_op4, p) || Path.equals(_op4, p)) {
var copy = onp.slice();
if (Path.endsBefore(_op4, onp) && _op4.length < onp.length) {
copy[_op4.length - 1] -= 1;
}
return copy.concat(p.slice(_op4.length));
} else if (Path.isSibling(_op4, onp) && (Path.isAncestor(onp, p) || Path.equals(onp, p))) {
if (Path.endsBefore(_op4, p)) {
p[_op4.length - 1] -= 1;
} else {
p[_op4.length - 1] += 1;
}
} else if (Path.endsBefore(onp, p) || Path.equals(onp, p) || Path.isAncestor(onp, p)) {
if (Path.endsBefore(_op4, p)) {
p[_op4.length - 1] -= 1;
}
p[onp.length - 1] += 1;
} else if (Path.endsBefore(_op4, p)) {
if (Path.equals(onp, p)) {
p[onp.length - 1] += 1;
}
p[_op4.length - 1] -= 1;
}
break;
}
}
return p;
}
};
var _typeof_1 = createCommonjsModule(function (module) {
function _typeof(o) {
"@babel/helpers - typeof";
return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
return typeof o;
} : function (o) {
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
}, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(o);
}
module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(_typeof_1);
var toPrimitive = createCommonjsModule(function (module) {
var _typeof = _typeof_1["default"];
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);
}
module.exports = _toPrimitive, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(toPrimitive);
var toPropertyKey = createCommonjsModule(function (module) {
var _typeof = _typeof_1["default"];
function _toPropertyKey(arg) {
var key = toPrimitive(arg, "string");
return _typeof(key) === "symbol" ? key : String(key);
}
module.exports = _toPropertyKey, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(toPropertyKey);
var defineProperty = createCommonjsModule(function (module) {
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;
}
module.exports = _defineProperty, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
var _defineProperty = unwrapExports(defineProperty);
var arrayWithHoles = createCommonjsModule(function (module) {
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
module.exports = _arrayWithHoles, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(arrayWithHoles);
var iterableToArrayLimit = createCommonjsModule(function (module) {
function _iterableToArrayLimit(r, l) {
var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
if (null != t) {
var e,
n,
i,
u,
a = [],
f = !0,
o = !1;
try {
if (i = (t = t.call(r)).next, 0 === l) {
if (Object(t) !== t) return;
f = !1;
} else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
} catch (r) {
o = !0, n = r;
} finally {
try {
if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return;
} finally {
if (o) throw n;
}
}
return a;
}
}
module.exports = _iterableToArrayLimit, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(iterableToArrayLimit);
var nonIterableRest = createCommonjsModule(function (module) {
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.");
}
module.exports = _nonIterableRest, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
unwrapExports(nonIterableRest);
var slicedToArray = createCommonjsModule(function (module) {
function _slicedToArray(arr, i) {
return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest();
}
module.exports = _slicedToArray, module.exports.__esModule = true, module.exports["default"] = module.exports;
});
var _slicedToArray = unwrapExports(slicedToArray);
var __defProp = Object.defineProperty;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
// src/utils/env.ts
var NOTHING = Symbol.for("immer-nothing");
var DRAFTABLE = Symbol.for("immer-draftable");
var DRAFT_STATE = Symbol.for("immer-state");
// src/utils/errors.ts
var errors = [
// All error codes, starting by 0:
function(plugin) {
return `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \`enable${plugin}()\` when initializing your application.`;
},
function(thing) {
return `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`;
},
"This object has been frozen and should not be mutated",
function(data) {
return "Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? " + data;
},
"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",
"Immer forbids circular references",
"The first or second argument to `produce` must be a function",
"The third argument to `produce` must be a function or undefined",
"First argument to `createDraft` must be a plain object, an array, or an immerable object",
"First argument to `finishDraft` must be a draft returned by `createDraft`",
function(thing) {
return `'current' expects a draft, got: ${thing}`;
},
"Object.defineProperty() cannot be used on an Immer draft",
"Object.setPrototypeOf() cannot be used on an Immer draft",
"Immer only supports deleting array indices",
"Immer only supports setting array indices and the 'length' property",
function(thing) {
return `'original' expects a draft, got: ${thing}`;
}
// Note: if more errors are added, the errorOffset in Patches.ts should be increased
// See Patches.ts for additional errors
] ;
function die(error, ...args) {
{
const e = errors[error];
const msg = typeof e === "function" ? e.apply(null, args) : e;
throw new Error(`[Immer] ${msg}`);
}
}
// src/utils/common.ts
var getPrototypeOf = Object.getPrototypeOf;
function isDraft(value) {
return !!value && !!value[DRAFT_STATE];
}
function isDraftable(value) {
var _a;
if (!value)
return false;
return isPlainObject$1(value) || Array.isArray(value) || !!value[DRAFTABLE] || !!((_a = value.constructor) == null ? void 0 : _a[DRAFTABLE]) || isMap(value) || isSet(value);
}
var objectCtorString = Object.prototype.constructor.toString();
function isPlainObject$1(value) {
if (!value || typeof value !== "object")
return false;
const proto = getPrototypeOf(value);
if (proto === null) {
return true;
}
const Ctor = Object.hasOwnProperty.call(proto, "constructor") && proto.constructor;
if (Ctor === Object)
return true;
return typeof Ctor == "function" && Function.toString.call(Ctor) === objectCtorString;
}
function each(obj, iter) {
if (getArchtype(obj) === 0 /* Object */) {
Object.entries(obj).forEach(([key, value]) => {
iter(key, value, obj);
});
} else {
obj.forEach((entry, index) => iter(index, entry, obj));
}
}
function getArchtype(thing) {
const state = thing[DRAFT_STATE];
return state ? state.type_ : Array.isArray(thing) ? 1 /* Array */ : isMap(thing) ? 2 /* Map */ : isSet(thing) ? 3 /* Set */ : 0 /* Object */;
}
function has(thing, prop) {
return getArchtype(thing) === 2 /* Map */ ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop);
}
function set(thing, propOrOldValue, value) {
const t = getArchtype(thing);
if (t === 2 /* Map */)
thing.set(propOrOldValue, value);
else if (t === 3 /* Set */) {
thing.add(value);
} else
thing[propOrOldValue] = value;
}
function is(x, y) {
if (x === y) {
return x !== 0 || 1 / x === 1 / y;
} else {
return x !== x && y !== y;
}
}
function isMap(target) {
return target instanceof Map;
}
function isSet(target) {
return target instanceof Set;
}
function latest(state) {
return state.copy_ || state.base_;
}
function shallowCopy(base, strict) {
if (isMap(base)) {
return new Map(base);
}
if (isSet(base)) {
return new Set(base);
}
if (Array.isArray(base))
return Array.prototype.slice.call(base);
if (!strict && isPlainObject$1(base)) {
if (!getPrototypeOf(base)) {
const obj = /* @__PURE__ */ Object.create(null);
return Object.assign(obj, base);
}
return __spreadValues({}, base);
}
const descriptors = Object.getOwnPropertyDescriptors(base);
delete descriptors[DRAFT_STATE];
let keys = Reflect.ownKeys(descriptors);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const desc = descriptors[key];
if (desc.writable === false) {
desc.writable = true;
desc.configurable = true;
}
if (desc.get || desc.set)
descriptors[key] = {
configurable: true,
writable: true,
// could live with !!desc.set as well here...
enumerable: desc.enumerable,
value: base[key]
};
}
return Object.create(getPrototypeOf(base), descriptors);
}
function freeze(obj, deep = false) {
if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj))
return obj;
if (getArchtype(obj) > 1) {
obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections;
}
Object.freeze(obj);
if (deep)
each(obj, (_key, value) => freeze(value, true));
return obj;
}
function dontMutateFrozenCollections() {
die(2);
}
function isFrozen(obj) {
return Object.isFrozen(obj);
}
// src/utils/plugins.ts
var plugins = {};
function getPlugin(pluginKey) {
const plugin = plugins[pluginKey];
if (!plugin) {
die(0, pluginKey);
}
return plugin;
}
// src/core/scope.ts
var currentScope;
function getCurrentScope() {
return currentScope;
}
function createScope(parent_, immer_) {
return {
drafts_: [],
parent_,
immer_,
// Whenever the modified draft contains a draft from another scope, we
// need to prevent auto-freezing so the unowned draft can be finalized.
canAutoFreeze_: true,
unfinalizedDrafts_: 0
};
}
function usePatchesInScope(scope, patchListener) {
if (patchListener) {
getPlugin("Patches");
scope.patches_ = [];
scope.inversePatches_ = [];
scope.patchListener_ = patchListener;
}
}
function revokeScope(scope) {
leaveScope(scope);
scope.drafts_.forEach(revokeDraft);
scope.drafts_ = null;
}
function leaveScope(scope) {
if (scope === currentScope) {
currentScope = scope.parent_;
}
}
function enterScope(immer2) {
return currentScope = createScope(currentScope, immer2);
}
function revokeDraft(draft) {
const state = draft[DRAFT_STATE];
if (state.type_ === 0 /* Object */ || state.type_ === 1 /* Array */)
state.revoke_();
else
state.revoked_ = true;
}
// src/core/finalize.ts
function processResult(result, scope) {
scope.unfinalizedDrafts_ = scope.drafts_.length;
const baseDraft = scope.drafts_[0];
const isReplaced = result !== void 0 && result !== baseDraft;
if (isReplaced) {
if (baseDraft[DRAFT_STATE].modified_) {
revokeScope(scope);
die(4);
}
if (isDraftable(result)) {
result = finalize(scope, result);
if (!scope.parent_)
maybeFreeze(scope, result);
}
if (scope.patches_) {
getPlugin("Patches").generateReplacementPatches_(
baseDraft[DRAFT_STATE].base_,
result,
scope.patches_,
scope.inversePatches_
);
}
} else {
result = finalize(scope, baseDraft, []);
}
revokeScope(scope);
if (scope.patches_) {
scope.patchListener_(scope.patches_, scope.inversePatches_);
}
return result !== NOTHING ? result : void 0;
}
function finalize(rootScope, value, path) {
if (isFrozen(value))
return value;
const state = value[DRAFT_STATE];
if (!state) {
each(
value,
(key, childValue) => finalizeProperty(rootScope, state, value, key, childValue, path));
return value;
}
if (state.scope_ !== rootScope)
return value;
if (!state.modified_) {
maybeFreeze(rootScope, state.base_, true);
return state.base_;
}
if (!state.finalized_) {
state.finalized_ = true;
state.scope_.unfinalizedDrafts_--;
const result = state.copy_;
let resultEach = result;
let isSet2 = false;
if (state.type_ === 3 /* Set */) {
resultEach = new Set(result);
result.clear();
isSet2 = true;
}
each(
resultEach,
(key, childValue) => finalizeProperty(rootScope, state, result, key, childValue, path, isSet2)
);
maybeFreeze(rootScope, result, false);
if (path && rootScope.patches_) {
getPlugin("Patches").generatePatches_(
state,
path,
rootScope.patches_,
rootScope.inversePatches_
);
}
}
return state.copy_;
}
function finalizeProperty(rootScope, parentState, targetObject, prop, childValue, rootPath, targetIsSet) {
if (childValue === targetObject)
die(5);
if (isDraft(childValue)) {
const path = rootPath && parentState && parentState.type_ !== 3 /* Set */ && // Set objects are atomic since they have no keys.
!has(parentState.assigned_, prop) ? rootPath.concat(prop) : void 0;
const res = finalize(rootScope, childValue, path);
set(targetObject, prop, res);
if (isDraft(res)) {
rootScope.canAutoFreeze_ = false;
} else
return;
} else if (targetIsSet) {
targetObject.add(childValue);
}
if (isDraftable(childValue) && !isFrozen(childValue)) {
if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {
return;
}
finalize(rootScope, childValue);
if (!parentState || !parentState.scope_.parent_)
maybeFreeze(rootScope, childValue);
}
}
function maybeFreeze(scope, value, deep = false) {
if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {
freeze(value, deep);
}
}
// src/core/proxy.ts
function createProxyProxy(base, parent) {
const isArray = Array.isArray(base);
const state = {
type_: isArray ? 1 /* Array */ : 0 /* Object */,
// Track which produce call this is associated with.
scope_: parent ? parent.scope_ : getCurrentScope(),
// True for both shallow and deep changes.
modified_: false,
// Used during finalization.
finalized_: false,
// Track which properties have been assigned (true) or deleted (false).
assigned_: {},
// The parent draft state.
parent_: parent,
// The base state.
base_: base,
// The base proxy.
draft_: null,
// set below
// The base copy with any updated values.
copy_: null,
// Called by the `produce` function.
revoke_: null,
isManual_: false
};
let target = state;
let traps = objectTraps;
if (isArray) {
target = [state];
traps = arrayTraps;
}
const { revoke, proxy } = Proxy.revocable(target, traps);
state.draft_ = proxy;
state.revoke_ = revoke;
return proxy;
}
var objectTraps = {
get(state, prop) {
if (prop === DRAFT_STATE)
return state;
const source = latest(state);
if (!has(source, prop)) {
return readPropFromProto(state, source, prop);
}
const value = source[prop];
if (state.finalized_ || !isDraftable(value)) {
return value;
}
if (value === peek(state.base_, prop)) {
prepareCopy(state);
return state.copy_[prop] = createProxy(value, state);
}
return value;
},
has(state, prop) {
return prop in latest(state);
},
ownKeys(state) {
return Reflect.ownKeys(latest(state));
},
set(state, prop, value) {
const desc = getDescriptorFromProto(latest(state), prop);
if (desc == null ? void 0 : desc.set) {
desc.set.call(state.draft_, value);
return true;
}
if (!state.modified_) {
const current2 = peek(latest(state), prop);
const currentState = current2 == null ? void 0 : current2[DRAFT_STATE];
if (currentState && currentState.base_ === value) {
state.copy_[prop] = value;
state.assigned_[prop] = false;
return true;
}
if (is(value, current2) && (value !== void 0 || has(state.base_, prop)))
return true;
prepareCopy(state);
markChanged(state);
}
if (state.copy_[prop] === value && // special case: handle new props with value 'undefined'
(value !== void 0 || prop in state.copy_) || // special case: NaN
Number.isNaN(value) && Number.isNaN(state.copy_[prop]))
return true;
state.copy_[prop] = value;
state.assigned_[prop] = true;
return true;
},
deleteProperty(state, prop) {
if (peek(state.base_, prop) !== void 0 || prop in state.base_) {
state.assigned_[prop] = false;
prepareCopy(state);
markChanged(state);
} else {
delete state.assigned_[prop];
}
if (state.copy_) {
delete state.copy_[prop];
}
return true;
},
// Note: We never coerce `desc.value` into an Immer draft, because we can't make
// the same guarantee in ES5 mode.
getOwnPropertyDescriptor(state, prop) {
const owner = latest(state);
const desc = Reflect.getOwnPropertyDescriptor(owner, prop);
if (!desc)
return desc;
return {
writable: true,
configurable: state.type_ !== 1 /* Array */ || prop !== "length",
enumerable: desc.enumerable,
value: owner[prop]
};
},
defineProperty() {
die(11);
},
getPrototypeOf(state) {
return getPrototypeOf(state.base_);
},
setPrototypeOf() {
die(12);
}
};
var arrayTraps = {};
each(objectTraps, (key, fn) => {
arrayTraps[key] = function() {
arguments[0] = arguments[0][0];
return fn.apply(this, arguments);
};
});
arrayTraps.deleteProperty = function(state, prop) {
if (isNaN(parseInt(prop)))
die(13);
return arrayTraps.set.call(this, state, prop, void 0);
};
arrayTraps.set = function(state, prop, value) {
if (prop !== "length" && isNaN(parseInt(prop)))
die(14);
return objectTraps.set.call(this, state[0], prop, value, state[0]);
};
function peek(draft, prop) {
const state = draft[DRAFT_STATE];
const source = state ? latest(state) : draft;
return source[prop];
}
function readPropFromProto(state, source, prop) {
var _a;
const desc = getDescriptorFromProto(source, prop);
return desc ? `value` in desc ? desc.value : (
// This is a very special case, if the prop is a getter defined by the
// prototype, we should invoke it with the draft as context!
(_a = desc.get) == null ? void 0 : _a.call(state.draft_)
) : void 0;
}
function getDescriptorFromProto(source, prop) {
if (!(prop in source))
return void 0;
let proto = getPrototypeOf(source);
while (proto) {
const desc = Object.getOwnPropertyDescriptor(proto, prop);
if (desc)
return desc;
proto = getPrototypeOf(proto);
}
return void 0;
}
function markChanged(state) {
if (!state.modified_) {
state.modified_ = true;
if (state.parent_) {
markChanged(state.parent_);
}
}
}
function prepareCopy(state) {
if (!state.copy_) {
state.copy_ = shallowCopy(
state.base_,
state.scope_.immer_.useStrictShallowCopy_
);
}
}
// src/core/immerClass.ts
var Immer2 = class {
constructor(config) {
this.autoFreeze_ = true;
this.useStrictShallowCopy_ = false;
/**
* The `produce` function takes a value and a "recipe function" (whose
* return value often depends on the base state). The recipe function is
* free to mutate its first argument however it wants. All mutations are
* only ever applied to a __copy__ of the base state.
*
* Pass only a function to create a "curried producer" which relieves you
* from passing the recipe function every time.
*
* Only plain objects and arrays are made mutable. All other objects are
* considered uncopyable.
*
* Note: This function is __bound__ to its `Immer` instance.
*
* @param {any} base - the initial state
* @param {Function} recipe - function that receives a proxy of the base state as first argument and which can be freely modified
* @param {Function} patchListener - optional function that will be called with all the patches produced here
* @returns {any} a new state, or the initial state if nothing was modified
*/
this.produce = (base, recipe, patchListener) => {
if (typeof base === "function" && typeof recipe !== "function") {
const defaultBase = recipe;
recipe = base;
const self = this;
return function curriedProduce(base2 = defaultBase, ...args) {
return self.produce(base2, (draft) => recipe.call(this, draft, ...args));
};
}
if (typeof recipe !== "function")
die(6);
if (patchListener !== void 0 && typeof patchListener !== "function")
die(7);
let result;
if (isDraftable(base)) {
const scope = enterScope(this);
const proxy = createProxy(base, void 0);
let hasError = true;
try {
result = recipe(proxy);
hasError = false;
} finally {
if (hasError)
revokeScope(scope);
else
leaveScope(scope);
}
usePatchesInScope(scope, patchListener);
return processResult(result, scope);
} else if (!base || typeof base !== "object") {
result = recipe(base);
if (result === void 0)
result = base;
if (result === NOTHING)
result = void 0;
if (this.autoFreeze_)
freeze(result, true);
if (patchListener) {
const p = [];
const ip = [];
getPlugin("Patches").generateReplacementPatches_(base, result, p, ip);
patchListener(p, ip);
}
return result;
} else
die(1, base);
};
this.produceWithPatches = (base, recipe) => {
if (typeof base === "function") {
return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args));
}
let patches, inversePatches;
const result = this.produce(base, recipe, (p, ip) => {
patches = p;
inversePatches = ip;
});
return [result, patches, inversePatches];
};
if (typeof (config == null ? void 0 : config.autoFreeze) === "boolean")
this.setAutoFreeze(config.autoFreeze);
if (typeof (config == null ? void 0 : config.useStrictShallowCopy) === "boolean")
this.setUseStrictShallowCopy(config.useStrictShallowCopy);
}
createDraft(base) {
if (!isDraftable(base))
die(8);
if (isDraft(base))
base = current(base);
const scope = enterScope(this);
const proxy = createProxy(base, void 0);
proxy[DRAFT_STATE].isManual_ = true;
leaveScope(scope);
return proxy;
}
finishDraft(draft, patchListener) {
const state = draft && draft[DRAFT_STATE];
if (!state || !state.isManual_)
die(9);
const { scope_: scope } = state;
usePatchesInScope(scope, patchListener);
return processResult(void 0, scope);
}
/**
* Pass true to automatically freeze all copies created by Immer.
*
* By default, auto-freezing is enabled.
*/
setAutoFreeze(value) {
this.autoFreeze_ = value;
}
/**
* Pass true to enable strict shallow copy.
*
* By default, immer does not copy the object descriptors such as getter, setter and non-enumrable properties.
*/
setUseStrictShallowCopy(value) {
this.useStrictShallowCopy_ = value;
}
applyPatches(base, patches) {
let i;
for (i = patches.length - 1; i >= 0; i--) {
const patch = patches[i];
if (patch.path.length === 0 && patch.op === "replace") {
base = patch.value;
break;
}
}
if (i > -1) {
patches = patches.slice(i + 1);
}
const applyPatchesImpl = getPlugin("Patches").applyPatches_;
if (isDraft(base)) {
return applyPatchesImpl(base, patches);
}
return this.produce(
base,
(draft) => applyPatchesImpl(draft, patches)
);
}
};
function createProxy(value, parent) {
const draft = isMap(value) ? getPlugin("MapSet").proxyMap_(value, parent) : isSet(value) ? getPlugin("MapSet").proxySet_(value, parent) : createProxyProxy(value, parent);
const scope = parent ? parent.scope_ : getCurrentScope();
scope.drafts_.push(draft);
return draft;
}
// src/core/current.ts
function current(value) {
if (!isDraft(value))
die(10, value);
return currentImpl(value);
}
function currentImpl(value) {
if (!isDraftable(value) || isFrozen(value))
return value;
const state = value[DRAFT_STATE];
let copy;
if (state) {
if (!state.modified_)
return state.base_;
state.finalized_ = true;
copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_);
} else {
copy = shallowCopy(value, true);
}
each(copy, (key, childValue) => {
set(copy, key, currentImpl(childValue));
});
if (state) {
state.finalized_ = false;
}
return copy;
}
// src/immer.ts
var immer = new Immer2();
var produce = immer.produce;
immer.produceWithPatches.bind(
immer
);
immer.setAutoFreeze.bind(immer);
immer.setUseStrictShallowCopy.bind(immer);
immer.applyPatches.bind(immer);
var createDraft = immer.createDraft.bind(immer);
var finishDraft = immer.finishDraft.bind(immer);
function ownKeys$e(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$e(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$e(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$e(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _createForOfIteratorHelper$m(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$m(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(_e) { throw _e; }, 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(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray$m(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$m(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$m(o, minLen); }
function _arrayLikeToArray$m(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; }
var applyToDraft = function applyToDraft(editor, selection, op) {
switch (op.type) {
case 'insert_node':
{
var path = op.path,
node = op.node;
var parent = Node.parent(editor, path);
var index = path[path.length - 1];
if (index > parent.children.length) {
throw new Error("Cannot apply an \"insert_node\" operation at path [".concat(path, "] because the destination is past the end of the node."));
}
parent.children.splice(index, 0, node);
if (selection) {
var _iterator = _createForOfIteratorHelper$m(Range.points(selection)),
_step;
try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var _step$value = _slicedToArray(_step.value, 2),
point = _step$value[0],
key = _step$value[1];
selection[key] = Point.transform(point, op);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}
}
break;
}
case 'insert_text':
{
var _path = op.path,
offset = op.offset,
text = op.text;
if (text.length === 0) break;
var _node = Node.leaf(editor, _path);
var before = _node.text.slice(0, offset);
var after = _node.text.slice(offset);
_node.text = before + text + after;
if (selection) {
var _iterator2 = _createForOfIteratorHelper$m(Range.points(selection)),
_step2;
try {
for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
var _step2$value = _slicedToArray(_step2.value, 2),
_point = _step2$value[0],
_key = _step2$value[1];
selection[_key] = Point.transform(_point, op);
}
} catch (err) {
_iterator2.e(err);
} finally {
_iterator2.f();
}
}
break;
}
case 'merge_node':
{
var _path2 = op.path;
var _node2 = Node.get(editor, _path2);
var prevPath = Path.previous(_path2);
var prev = Node.get(editor, prevPath);
var _parent = Node.parent(editor, _path2);
var _index = _path2[_path2.length - 1];
if (Text.isText(_node2) && Text.isText(prev)) {
prev.text += _node2.text;
} else if (!Text.isText(_node2) && !Text.isText(prev)) {
var _prev$children;
(_prev$children = prev.children).push.apply(_prev$children, _toConsumableArray(_node2.children));
} else {
throw new Error("Cannot apply a \"merge_node\" operation at path [".concat(_path2, "] to nodes of different interfaces: ").concat(Scrubber.stringify(_node2), " ").concat(Scrubber.stringify(prev)));
}
_parent.children.splice(_index, 1);
if (selection) {
var _iterator3 = _createForOfIteratorHelper$m(Range.points(selection)),
_step3;
try {
for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
var _step3$value = _slicedToArray(_step3.value, 2),
_point2 = _step3$value[0],
_key2 = _step3$value[1];
selection[_key2] = Point.transform(_point2, op);
}
} catch (err) {
_iterator3.e(err);
} finally {
_iterator3.f();
}
}
break;
}
case 'move_node':
{
var _path3 = op.path,
newPath = op.newPath;
if (Path.isAncestor(_path3, newPath)) {
throw new Error("Cannot move a path [".concat(_path3, "] to new path [").concat(newPath, "] because the destination is inside itself."));
}
var _node3 = Node.get(editor, _path3);
var _parent2 = Node.parent(editor, _path3);
var _index2 = _path3[_path3.length - 1];
// This is tricky, but since the `path` and `newPath` both refer to
// the same snapshot in time, there's a mismatch. After either
// removing the original position, the second step's path can be out
// of date. So instead of using the `op.newPath` directly, we
// transform `op.path` to ascertain what the `newPath` would be after
// the operation was applied.
_parent2.children.splice(_index2, 1);
var truePath = Path.transform(_path3, op);
var newParent = Node.get(editor, Path.parent(truePath));
var newIndex = truePath[truePath.length - 1];
newParent.children.splice(newIndex, 0, _node3);
if (selection) {
var _iterator4 = _createForOfIteratorHelper$m(Range.points(selection)),
_step4;
try {
for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
var _step4$value = _slicedToArray(_step4.value, 2),
_point3 = _step4$value[0],
_key3 = _step4$value[1];
selection[_key3] = Point.transform(_point3, op);
}
} catch (err) {
_iterator4.e(err);
} finally {
_iterator4.f();
}
}
break;
}
case 'remove_node':
{
var _path4 = op.path;
var _index3 = _path4[_path4.length - 1];
var _parent3 = Node.parent(editor, _path4);
_parent3.children.splice(_index3, 1);
// Transform all the points in the value, but if the point was in the
// node that was removed we need to update the range or remove it.
if (selection) {
var _iterator5 = _createForOfIteratorHelper$m(Range.points(selection)),
_step5;
try {
for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
var _step5$value = _slicedToArray(_step5.value, 2),