UNPKG

@atlaskit/editor-plugin-local-id

Version:

LocalId plugin for @atlaskit/editor-core

57 lines (56 loc) • 2.17 kB
import { BatchAttrsStep } from '@atlaskit/adf-schema/steps/batch-attrs-step'; import { tintDirtyTransaction } from '@atlaskit/editor-common/collab'; import { generateShortUUID, generatedShortUUIDs } from './generateShortUUID'; export const localIdNotEmpty = localId => typeof localId === 'string' && localId.trim().length > 0; export const addMissingLocalIdsToDocument = (tr, { onRepaired } = {}) => { const missingLocalIdPositions = []; const { text, hardBreak, mediaGroup } = tr.doc.type.schema.nodes; const ignoredNodeTypes = [text === null || text === void 0 ? void 0 : text.name, hardBreak === null || hardBreak === void 0 ? void 0 : hardBreak.name, mediaGroup === null || mediaGroup === void 0 ? void 0 : mediaGroup.name]; tr.doc.descendants((node, pos) => { var _node$type$spec$attrs; if (localIdNotEmpty(node.attrs.localId)) { generatedShortUUIDs.add(node.attrs.localId); } else if (!ignoredNodeTypes.includes(node.type.name) && !!((_node$type$spec$attrs = node.type.spec.attrs) !== null && _node$type$spec$attrs !== void 0 && _node$type$spec$attrs.localId)) { missingLocalIdPositions.push(pos); } return true; }); const nodesToUpdate = new Map(missingLocalIdPositions.map(pos => [pos, generateShortUUID()])); if (nodesToUpdate.size === 0) { return false; } batchAddLocalIdToNodes(nodesToUpdate, tr); tintDirtyTransaction(tr); onRepaired === null || onRepaired === void 0 ? void 0 : onRepaired({ repairedNodeCount: nodesToUpdate.size }); return true; }; /** * Batch adds local IDs to nodes using a BatchAttrsStep * @param nodesToUpdate Map of position -> localId for nodes that need updates * @param tr */ export const batchAddLocalIdToNodes = (nodesToUpdate, tr) => { const batchData = Array.from(nodesToUpdate.entries()).map(([pos, localId]) => { const node = tr.doc.nodeAt(pos); if (!node) { throw new Error(`Node does not exist at position ${pos}`); } return { position: pos, attrs: { localId }, nodeType: node.type.name }; }); tr.step(new BatchAttrsStep(batchData)); tr.setMeta('addToHistory', false); };