UNPKG

@atlaskit/adf-schema

Version:

Shared package that contains the ADF-schema (json) and ProseMirror node/mark specs

55 lines (52 loc) 2.07 kB
export function sanitizeNodes(nodes, supportedMarks) { const nodeNames = Object.keys(nodes); nodeNames.forEach(nodeKey => { const nodeSpec = { ...nodes[nodeKey] }; if (nodeSpec.marks && nodeSpec.marks !== '_') { // eslint-disable-next-line @atlassian/perf-linting/no-expensive-split-replace -- Ignored via go/ees017 (to be fixed) nodeSpec.marks = nodeSpec.marks.split(' ').filter(mark => !!supportedMarks[mark]).join(' '); } if (nodeSpec.content) { nodeSpec.content = sanitizeNodeSpecContent(nodes, nodeSpec.content); } nodes[nodeKey] = nodeSpec; }); return nodes; } function sanitizeNodeSpecContent(nodes, rawContent) { // @ts-ignore TS1501: This regular expression flag is only available when targeting 'es6' or later. const content = rawContent.replace(/\W/gu, ' '); const contentKeys = content.split(' '); const unsupportedContentKeys = contentKeys.filter(contentKey => !isContentSupported(nodes, contentKey)); return unsupportedContentKeys.reduce((newContent, nodeName) => sanitizedContent(newContent, nodeName), rawContent); } function sanitizedContent(content, invalidContent) { if (!invalidContent.length) { return content || ''; } // @ts-ignore TS1501: This regular expression flag is only available when targeting 'es6' or later. if (!content || !content.match(/\w/u)) { return ''; } const pattern = `(${invalidContent}((\\s)*\\|)+)|((\\|(\\s)*)+${invalidContent}(\\+|\\*)?)|(${invalidContent}$)|(${invalidContent}(\\+|\\*))`; return content.replace(new RegExp(pattern, 'gu'), '').replace(' ', ' ').trim(); } function isContentSupported(nodes, contentKey) { const nodeKeys = Object.keys(nodes); // content is with valid node if (nodeKeys.indexOf(contentKey) > -1) { return true; } // content is with valid group for (const supportedKey in nodes) { if (nodes.hasOwnProperty(supportedKey)) { const nodeSpec = nodes[supportedKey]; if (nodeSpec && nodeSpec.group === contentKey) { return true; } } } return false; }