UNPKG

@atlaskit/adf-schema

Version:

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

59 lines (56 loc) 2.3 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 = Array.from(new Set(contentKeys.filter(contentKey => !isContentSupported(nodes, contentKey))) // Remove longer variant names first so base names like `panel` don't partially strip `panel_c1`. ).sort((a, b) => b.length - a.length); return unsupportedContentKeys.reduce((newContent, nodeName) => sanitizedContent(newContent, nodeName), rawContent); } // @ts-ignore TS1501: This regular expression flag is only available when targeting 'es6' or later. const WORD_CHAR_REGEX = /\w/u; function sanitizedContent(content, invalidContent) { if (!invalidContent.length) { return content || ''; } if (!content || !content.match(WORD_CHAR_REGEX)) { return ''; } const pattern = `(${invalidContent}((\\s)*\\|)+)|((\\|(\\s)*)+${invalidContent}(\\+|\\*)?)|(${invalidContent}$)|(${invalidContent}(\\+|\\*))`; // Ignored via go/ees019 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; }