UNPKG

@atlaskit/renderer

Version:
60 lines (54 loc) 3.01 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.removeEmptySpaceAroundContent = void 0; var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } var removeEmptySpaceAroundContent = exports.removeEmptySpaceAroundContent = function removeEmptySpaceAroundContent(document) { // Check if the document is valid if (!document || !document.content || !Array.isArray(document.content)) { return document; } // Check if the node is a meaningful content node meaning it is not an empty paragraph or a paragraph with only whitespace var isMeaningfulContentNode = function isMeaningfulContentNode(node) { // Check if the node is a non-empty paragraph or a non-paragraph node if (node.type !== 'paragraph') { return true; } // If the paragraph is empty, return false if (!node.content || node.content.length === 0) { return false; } // Check if paragraph has any content other than `hardBreak` or whitespace text nodes return node.content.some(function (child) { return !((child === null || child === void 0 ? void 0 : child.type) === 'hardBreak' || (child === null || child === void 0 ? void 0 : child.type) === 'text' && typeof child.text === 'string' && child.text.trim() === ''); }); }; var content = document.content; var firstContentIndex = -1; var lastContentIndex = -1; // Find the first and last paragraphs with content and check if they are meaningful for (var i = 0; i < content.length; i++) { if (isMeaningfulContentNode(content[i])) { if (firstContentIndex === -1) { firstContentIndex = i; } lastContentIndex = i; } } // If no content was found, return an empty document if (firstContentIndex === -1) { return _objectSpread(_objectSpread({}, document), {}, { content: [] }); } // Slice the content array to include only paragraphs between the first and last content var trimmedContent = content.slice(firstContentIndex, lastContentIndex + 1); // Return a new document with the trimmed content return _objectSpread(_objectSpread({}, document), {}, { content: trimmedContent }); };