From dbb79160591093ff2603e182a0a088bc36473cb3 Mon Sep 17 00:00:00 2001 From: Artur Arseniev Date: Thu, 18 Jul 2019 20:44:22 +0200 Subject: [PATCH] Add processor option to DomComponents module --- src/dom_components/config/config.js | 21 +++++++++++++++++++++ src/dom_components/model/Components.js | 14 +++++++++++--- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/dom_components/config/config.js b/src/dom_components/config/config.js index 7e32cc61f..1845c3255 100644 --- a/src/dom_components/config/config.js +++ b/src/dom_components/config/config.js @@ -36,6 +36,27 @@ export default { // as we need to store inlined style. storeWrapper: 0, + /** + * You can setup a custom component definiton processor before adding it into the editor. + * It might be useful to transform custom objects (es. some framework specific JSX) to GrapesJS component one. + * This custom function will be executed on ANY new added component to the editor so make smart checks/conditions + * to avoid doing useless executions + * By default, GrapesJS supports already React Element + * @example + * processor: (obj) => { + * if (obj.$$typeof) { // eg. this is a React Element + * const gjsComponent = { + * type: obj.type, + * components: obj.props.children, + * ... + * }; + * ... + * return gjsComponent; + * } + * } + */ + processor: 0, + // List of void elements voidElements: [ 'area', diff --git a/src/dom_components/model/Components.js b/src/dom_components/model/Components.js index fb54073e5..b51a59b8e 100644 --- a/src/dom_components/model/Components.js +++ b/src/dom_components/model/Components.js @@ -1,5 +1,5 @@ import Backbone from 'backbone'; -import { isEmpty, isArray, isString, each, includes } from 'underscore'; +import { isEmpty, isArray, isString, each, includes, extend } from 'underscore'; let Component; @@ -82,9 +82,17 @@ export default Backbone.Collection.extend({ * Process component definition. */ processDef(model) { + const { em, config } = this; + const { processor } = config; + + const modelPr = processor && processor(model); + if (modelPr) { + each(model, (val, key) => delete model[key]); + extend(model, modelPr); + } + // React JSX if (model.$$typeof && typeof model.props == 'object') { - const { em } = this; const domc = em.get('DomComponents'); const parser = em.get('Parser'); const { parserHtml } = parser; @@ -109,7 +117,7 @@ export default Backbone.Collection.extend({ delete model.type; } - each(res.props, (val, key) => (model[key] = val)); + extend(model, res.props); } return model;