json-joy
Version:
Collection of libraries for building collaborative editing apps.
30 lines (29 loc) • 1.13 kB
JavaScript
import { isRoot, isValidIndex, isChild, formatJsonPointer } from '@jsonjoy.com/json-pointer';
import { bumpArrayPath } from './util';
import { operationToOp } from '../../json-patch/codec/json';
export const xAdd = (add, op) => {
if (isRoot(add.path))
return null;
if (isRoot(op.path))
return op;
const lastIndex = add.path.length - 1;
const lastStep = add.path[lastIndex];
const isLastStepNumberLike = isValidIndex(lastStep);
if (isChild(add.path, op.path) && !isLastStepNumberLike)
return null;
if (isLastStepNumberLike) {
const newPath = bumpArrayPath(add.path, op.path);
const newFrom = op.from ? bumpArrayPath(add.path, op.from) : undefined;
if (newPath || newFrom) {
const operation = {
...op.toJson(),
path: newPath ? formatJsonPointer(newPath) : op.path,
};
if (newFrom)
operation.from = formatJsonPointer(newFrom);
// TODO: The second argument should not be {}
return operationToOp(operation, {});
}
}
return op;
};