json-joy
Version:
Collection of libraries for building collaborative editing apps.
90 lines (89 loc) • 2.67 kB
JavaScript
import { isEmpty } from '@jsonjoy.com/util/lib/isEmpty';
import { PersistedSlice } from '../peritext/slice/PersistedSlice';
import { SliceStacking } from '../peritext/slice/constants';
export const getAttributes = (overlayPoint) => {
const layers = overlayPoint.layers;
const layerLength = layers.length;
if (!layerLength)
return;
const attributes = {};
for (let i = 0; i < layerLength; i++) {
const slice = layers[i];
if (!(slice instanceof PersistedSlice))
continue;
switch (slice.stacking) {
case SliceStacking.One: {
const tag = slice.type;
if (tag)
attributes[tag] = slice.data();
break;
}
case SliceStacking.Erase: {
const tag = slice.type;
if (tag)
delete attributes[tag];
break;
}
}
}
if (isEmpty(attributes))
return undefined;
return attributes;
};
const eraseAttributes = (attr) => {
if (!attr)
return;
const keys = Object.keys(attr);
const length = keys.length;
if (!length)
return;
const erased = {};
for (let i = 0; i < length; i++)
erased[keys[i]] = null;
return erased;
};
export const removeErasures = (attr) => {
if (!attr)
return;
const keys = Object.keys(attr);
const length = keys.length;
if (!length)
return;
const cleaned = {};
for (let i = 0; i < length; i++) {
const key = keys[i];
const value = attr[key];
if (value !== null)
cleaned[key] = value;
}
return isEmpty(cleaned) ? undefined : cleaned;
};
export const diffAttributes = (oldAttributes, newAttributes) => {
if (!oldAttributes)
return removeErasures(newAttributes);
if (!newAttributes)
return eraseAttributes(oldAttributes);
const diff = {};
const keys = Object.keys(newAttributes);
const length = keys.length;
for (let i = 0; i < length; i++) {
const key = keys[i];
const newValue = newAttributes[key];
const oldValue = oldAttributes[key];
if (newValue === oldValue)
continue;
diff[key] = newValue;
}
const oldKeys = Object.keys(oldAttributes);
const oldLength = oldKeys.length;
for (let i = 0; i < oldLength; i++) {
const key = oldKeys[i];
// tslint:disable-next-line:triple-equals
if (newAttributes[key] !== undefined)
continue;
diff[key] = null;
}
if (isEmpty(diff))
return undefined;
return diff;
};