UNPKG

@atlaskit/adf-utils

Version:

Set of utilities to traverse, modify and create ADF documents.

64 lines (63 loc) 2.24 kB
import { traverse } from '../traverse/traverse'; import { validator } from '../validator/validator'; var NATIVE_EMBED_EXTENSION_KEY = 'native-embed'; /** * Replaces any `extension` nodes whose `extensionKey` is * `native-embed` with a paragraph containing an `inlineCard` * node pointing at the same URL. * If a native-embed node has no URL it is dropped from the document. * * The transformed ADF is validated against the ADF spec. * If validation fails the original (untransformed) ADF is returned * to avoid rendering broken content. */ export var nativeEmbedsFallbackTransform = function nativeEmbedsFallbackTransform(adf) { var didTransform = false; var transformedAdf = traverse(adf, { extension: function extension(node) { var _node$attrs, _node$attrs2; if (((_node$attrs = node.attrs) === null || _node$attrs === void 0 ? void 0 : _node$attrs['extensionKey'].split(':')[0]) !== NATIVE_EMBED_EXTENSION_KEY) { return node; } var url = (_node$attrs2 = node.attrs) === null || _node$attrs2 === void 0 || (_node$attrs2 = _node$attrs2['parameters']) === null || _node$attrs2 === void 0 || (_node$attrs2 = _node$attrs2.macroParams) === null || _node$attrs2 === void 0 || (_node$attrs2 = _node$attrs2.url) === null || _node$attrs2 === void 0 ? void 0 : _node$attrs2.value; if (!url) { didTransform = true; return false; } didTransform = true; return { type: 'paragraph', content: [{ type: 'inlineCard', attrs: { url: url } }] }; } }); if (didTransform && transformedAdf) { try { var validate = validator(); var _validate = validate(transformedAdf), valid = _validate.valid; if (!valid) { // Transformed ADF is invalid – fall back to the original document return { transformedAdf: adf, hasValidTransform: false }; } } catch (_unused) { // Validation threw – fall back to the original document return { transformedAdf: adf, hasValidTransform: false }; } } return { transformedAdf: transformedAdf, hasValidTransform: didTransform }; };