UNPKG

convert-draftjs

Version:

Easily convert the result of DraftJS into useful and easy to read data. For example; Array of text, plain text, etc.

101 lines (84 loc) 2.87 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function parseDraftResult(draftResult) { /** * If draftResult is in stringify mode, * then parse to JSON. If not simply return back. */ if (typeof draftResult === 'string') { return JSON.parse(draftResult); } return draftResult; } function convertDraftToArray(draftResult, options) { var _options$select, _options$includeBlank; /** * Parsed DraftJS result. * When input is string that means its not parsed yet. */ var parsedDraft = parseDraftResult(draftResult); /** * Array containing the result */ var parsedArray = []; /** * Selector options. * This selector used to determine what blocks should * be extracted, either all, unstyled, header, or code block. * * default value is 'all' * * @see SelectValue */ var selector = (_options$select = options == null ? void 0 : options.select) != null ? _options$select : ['all']; /** * Do you want to keep blank blocks? * blank blocks are used to indicate enter or "< br />" tag. * if true the result may contain blank strings. */ var includeBlank = (_options$includeBlank = options == null ? void 0 : options.includeBlank) != null ? _options$includeBlank : false; /** * Loop through parsedDraft, * search for selector that specified in the options * and return back value as an array. */ parsedDraft.blocks.forEach(function (value) { if ((!includeBlank ? value.text.length > 0 : true) && (selector[0] !== 'all' ? selector.includes(value.type) : true)) { parsedArray.push(value.text); } }); return parsedArray; } /** * @param draftResult (JSON or Strings) * @param options */ function convertDraftToPlain(draftResult, options) { var _options$join, _options$includeCount; var joinElement = (_options$join = options == null ? void 0 : options.join) != null ? _options$join : ' '; /** * Do you want to include char and word counter? * if true it will return result with sum of chars and words. * @default ' ' */ var isIncludeCounter = (_options$includeCount = options == null ? void 0 : options.includeCounter) != null ? _options$includeCount : false; var result = convertDraftToArray(draftResult, options).join(joinElement); if (isIncludeCounter) { var chars = result.length; var words = joinElement.length > 0 ? result.split(joinElement).filter(function (n) { return n != joinElement; }).length : 1; return { result: result, chars: chars, words: words }; } return { result: result }; } exports.convertDraftToArray = convertDraftToArray; exports.convertDraftToPlain = convertDraftToPlain; exports.parseDraftResult = parseDraftResult; //# sourceMappingURL=convert-draftjs.cjs.development.js.map