@atlaskit/adf-schema
Version:
Shared package that contains the ADF-schema (json) and ProseMirror node/mark specs
184 lines (183 loc) • 7.75 kB
JavaScript
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import _possibleConstructorReturn from "@babel/runtime/helpers/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/getPrototypeOf";
import _inherits from "@babel/runtime/helpers/inherits";
import _typeof from "@babel/runtime/helpers/typeof";
function ownKeys(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) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
import { Fragment, Slice } from '@atlaskit/editor-prosemirror/model';
import { Step, StepResult } from '@atlaskit/editor-prosemirror/transform';
var stepType = 'batchAttrs';
var isValidData = function isValidData(data) {
if (data !== null && !Array.isArray(data)) {
return false;
}
return !data.some(function (d) {
var invalidPosition = typeof d.position !== 'number';
var invalidNodeType = typeof d.nodeType !== 'string';
var invalidAttrs = _typeof(d.attrs) !== 'object';
return invalidPosition || invalidNodeType || invalidAttrs;
});
};
/**
* 📢 Public API: Editor FE Platform
*
* Represents a step that applies a batch of attribute changes to nodes in a ProseMirror document.
*
* This step is particularly useful when you need to update the attributes of multiple nodes in a document
* in a single operation. For example, you might want to change the color of several panels or update metadata
* for various sections without needing to perform multiple separate operations.
*
* **Use Cases:**
* - **Efficiency**: Apply multiple attribute changes in a single step to reduce the number of operations.
* - **Atomicity**: Ensure that a group of attribute changes are applied together, maintaining document consistency.
* - **Consistency**: Use when changes are logically related, such as updating theme attributes for a document section.
*
* **When Not to Use:**
* - **Single Changes**: If you only need to change attributes on a single node, a more straightforward step might be suitable like `AttrsStep` from prosemirror.
* - **Complex Node Transformations**: This step is designed for attribute changes rather than structural changes.
* - **Performance Concerns**: While efficient for batch updates, unnecessary use for single updates may add overhead.
*
* @example
* ```typescript
* import { BatchAttrsStep } from '@atlaskit/adf-schema/steps';
*
* // Define the attribute changes
* const changes = [
* {
* position: 0, // Position of the first panel
* nodeType: 'panel',
* attrs: { panelType: 'error' }
* },
* {
* position: 7, // Position of the second panel
* nodeType: 'panel',
* attrs: { panelType: 'success' }
* }
* ];
*
* // Create the step and apply it to the document
* const step = new BatchAttrsStep(changes);
*
* const tr = editorState.tr;
*
* tr.step(step);
* ```
*
* @class
* @extends {Step}
*/
export var BatchAttrsStep = /*#__PURE__*/function (_Step) {
function BatchAttrsStep(data) {
var _this;
var inverted = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
_classCallCheck(this, BatchAttrsStep);
_this = _callSuper(this, BatchAttrsStep);
_this.data = data;
_this.inverted = inverted;
return _this;
}
_inherits(BatchAttrsStep, _Step);
return _createClass(BatchAttrsStep, [{
key: "apply",
value: function apply(doc) {
var resultDoc = this.data.reduce(function (acc, value) {
var _acc$doc;
if (!acc.doc || acc.failed) {
return acc;
}
var position = value.position,
attrs = value.attrs;
if (acc.doc && position > acc.doc.nodeSize || position < 0) {
return StepResult.fail("Position ".concat(position, " out of document range."));
}
var target = (_acc$doc = acc.doc) === null || _acc$doc === void 0 ? void 0 : _acc$doc.nodeAt(position);
if (!target) {
return StepResult.fail("No node at given position: ".concat(position));
}
if (target.isText) {
return StepResult.fail('Target is a text node. Attributes are not allowed.');
}
var mergedAttrs = _objectSpread(_objectSpread({}, target.attrs || {}), attrs || {});
var updatedNode = target.type.create(mergedAttrs, null, target.marks);
var slice = new Slice(Fragment.from(updatedNode), 0, target.isLeaf ? 0 : 1);
return StepResult.fromReplace(acc.doc, position, position + 1, slice);
}, StepResult.ok(doc));
return resultDoc;
}
}, {
key: "invert",
value: function invert(doc) {
var previousData = this.data.reduce(function (acc, value) {
var position = value.position,
nodeType = value.nodeType,
nextAttrs = value.attrs;
if (position > doc.nodeSize) {
return acc;
}
var target = doc.nodeAt(position);
if (!target) {
return acc;
}
if (target.isText) {
return acc;
}
var previousAttrs = Object.keys(nextAttrs).reduce(function (attributesIterator, key) {
var oldValue = target.attrs[key];
attributesIterator[key] = oldValue;
return attributesIterator;
}, {});
var prev = {
position: position,
nodeType: nodeType,
attrs: previousAttrs
};
acc.push(prev);
return acc;
}, []);
return new BatchAttrsStep(previousData, true);
}
}, {
key: "map",
value: function map(mapping) {
var mappedData = this.data.reduce(function (acc, value) {
var position = value.position;
var mappedPosition = mapping.mapResult(position);
if (mappedPosition.deleted) {
return acc;
}
acc.push(_objectSpread(_objectSpread({}, value), {}, {
position: mappedPosition.pos
}));
return acc;
}, []);
if (mappedData.length === 0) {
return null;
}
return new BatchAttrsStep(mappedData, this.inverted);
}
}, {
key: "toJSON",
value: function toJSON() {
return {
stepType: stepType,
data: this.data,
inverted: this.inverted
};
}
}], [{
key: "fromJSON",
value: function fromJSON(_schema, json) {
var data = json === null || json === void 0 ? void 0 : json.data;
if (!isValidData(data)) {
throw new Error('Invalid input for BatchAttrsStep.fromJSON');
}
return new BatchAttrsStep(data, Boolean(json.inverted));
}
}]);
}(Step);
Step.jsonID(stepType, BatchAttrsStep);