UNPKG

@lyra/form-builder

Version:
91 lines (74 loc) 2.75 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = PastePlugin; var _slate = require('slate'); var _slateReact = require('slate-react'); var _blockTools = require('@lyra/block-tools'); var _blockTools2 = _interopRequireDefault(_blockTools); var _randomKey = require('../utils/randomKey'); var _randomKey2 = _interopRequireDefault(_randomKey); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function processNode(node) { if (!node.get('nodes')) { return node; } const newKey = (0, _randomKey2.default)(12); const SlateType = node.constructor; const newData = node.get('data') ? node.get('data').toObject() : {}; newData._key = newKey; if (newData.value && newData.value._key) { newData.value._key = newKey; } if (newData.annotations) { Object.keys(newData.annotations).forEach(key => { newData.annotations[key]._key = (0, _randomKey2.default)(12); }); } return new SlateType({ data: _slate.Data.create(newData), isVoid: node.get('isVoid'), key: newKey, nodes: node.get('nodes').map(processNode), type: node.get('type') }); } function PastePlugin(options /*: Options*/ = {}) { const blockContentType = options.blockContentType; if (!blockContentType) { throw new Error("Missing required option 'blockContentType'"); } function onPaste(event, change, editor) { event.preventDefault(); const shiftKey = event.shiftKey; const transfer = (0, _slateReact.getEventTransfer)(event); const fragment = transfer.fragment, html = transfer.html; let type = transfer.type; if (type === 'fragment') { // Check if we have all block types in the schema, // otherwise, use html version const allSchemaBlockTypes = blockContentType.of.map(ofType => ofType.name).concat('contentBlock'); const allBlocksHasSchemaDef = fragment.nodes.map(node => node.type).every(nodeType => allSchemaBlockTypes.includes(nodeType)); if (allBlocksHasSchemaDef) { const newNodesList = _slate.Block.createList(fragment.nodes.map(processNode)); const newDoc = new _slate.Document({ key: fragment.key, nodes: newNodesList }); return change.insertFragment(newDoc).collapseToEndOfBlock(); } type = 'html'; } if (type === 'html' && !shiftKey) { const blocks = _blockTools2.default.htmlToBlocks(html, blockContentType); const doc = _slate.Document.fromJSON(_blockTools2.default.blocksToEditorValue(blocks, blockContentType).document); return change.insertFragment(doc).collapseToEndOfBlock(); } return undefined; } return { onPaste }; }