@atlaskit/adf-utils
Version:
Set of utilities to traverse, modify and create ADF documents.
65 lines (64 loc) • 2.33 kB
JavaScript
import { traverse } from '../traverse/traverse';
import { validator } from '../validator/validator';
const 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 const nativeEmbedsFallbackTransform = adf => {
let didTransform = false;
const transformedAdf = traverse(adf, {
extension: node => {
var _node$attrs, _node$attrs2, _node$attrs2$paramete, _node$attrs2$paramete2, _node$attrs2$paramete3;
if (((_node$attrs = node.attrs) === null || _node$attrs === void 0 ? void 0 : _node$attrs['extensionKey'].split(':')[0]) !== NATIVE_EMBED_EXTENSION_KEY) {
return node;
}
const url = (_node$attrs2 = node.attrs) === null || _node$attrs2 === void 0 ? void 0 : (_node$attrs2$paramete = _node$attrs2['parameters']) === null || _node$attrs2$paramete === void 0 ? void 0 : (_node$attrs2$paramete2 = _node$attrs2$paramete.macroParams) === null || _node$attrs2$paramete2 === void 0 ? void 0 : (_node$attrs2$paramete3 = _node$attrs2$paramete2.url) === null || _node$attrs2$paramete3 === void 0 ? void 0 : _node$attrs2$paramete3.value;
if (!url) {
didTransform = true;
return false;
}
didTransform = true;
return {
type: 'paragraph',
content: [{
type: 'inlineCard',
attrs: {
url
}
}]
};
}
});
if (didTransform && transformedAdf) {
try {
const validate = validator();
const {
valid
} = validate(transformedAdf);
if (!valid) {
// Transformed ADF is invalid – fall back to the original document
return {
transformedAdf: adf,
hasValidTransform: false
};
}
} catch {
// Validation threw – fall back to the original document
return {
transformedAdf: adf,
hasValidTransform: false
};
}
}
return {
transformedAdf,
hasValidTransform: didTransform
};
};