UNPKG

@qonsoll/component-builder

Version:

This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).

1,228 lines (1,034 loc) 324 kB
import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties'; import { Row, Col, Box, Container, NoData, Text, Button, Icon, Dropdown, Switch, Input as Input$1, Popover, Title, Divider, Select as Select$1, Option, TextArea } from '@qonsoll/react-design'; import { Result, Select, Tooltip, notification, Menu, Tag, Input, Modal, Button as Button$1, Tree as Tree$1, Form, Tabs, Checkbox } from 'antd'; import { jsx, Fragment, jsxs } from 'react/jsx-runtime'; import PropTypes from 'prop-types'; import { createContext, useContext, useCallback, useState, useEffect, useRef, useMemo, memo, Fragment as Fragment$1, useReducer } from 'react'; import _defineProperty from '@babel/runtime/helpers/defineProperty'; import _slicedToArray from '@babel/runtime/helpers/slicedToArray'; import { useKeyPress, useHover } from '@umijs/hooks'; import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray'; import _taggedTemplateLiteral from '@babel/runtime/helpers/taggedTemplateLiteral'; import styled from 'styled-components'; import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator'; import _regeneratorRuntime from '@babel/runtime/regenerator'; import { getFirestore, doc, getDoc, serverTimestamp, setDoc, updateDoc } from 'firebase/firestore'; import { initializeApp } from 'firebase/app'; import { nanoid } from 'nanoid'; import _ from 'lodash'; import { MdCode, MdOutlineViewQuilt, MdOutlineKeyboard, MdPhonelinkErase, MdStayCurrentPortrait } from 'react-icons/md'; import Handlebars from 'handlebars'; import * as NextLibElements from '@qonsoll/qonstructor-next-components'; import * as ReactLibElements from '@qonsoll/qonstructor-react-components'; import { PlusOutlined, FileImageOutlined, CloudSyncOutlined, DownOutlined, CloseOutlined } from '@ant-design/icons'; import { useParams } from 'react-router-dom'; import * as htmlToImage from 'html-to-image'; import Draggable from 'react-draggable'; import _typeof from '@babel/runtime/helpers/typeof'; import 'moment'; var NotFoundPage = function NotFoundPage() { // const navigate = useNavigate() // const handleBack = () => navigate(-1) // const handleHome = () => navigate('/', { replace: true }) return /*#__PURE__*/jsx(Row, { h: "center", v: "center", height: "inherit", children: /*#__PURE__*/jsx(Col, { cw: "auto", children: /*#__PURE__*/jsx(Result, { status: "404", title: "404", subTitle: 'Sorry, the page you visited does not exist' // extra={ // <Box display="flex" justifyContent="space-evenly"> // <Button onClick={handleBack}>Back</Button> // <Button onClick={handleHome} type="primary"> // Home // </Button> // </Box> // } }) }) }); }; var LayotContext = /*#__PURE__*/createContext(); var EventsContext = /*#__PURE__*/createContext(); var ComponentBuilderContext = /*#__PURE__*/createContext(); var useComponentBuilder = function useComponentBuilder() { return useContext(ComponentBuilderContext); }; var useStateActions = function useStateActions(dispatch) { var addComponent = useCallback(function (payload) { return dispatch({ type: 'add', payload: payload }); }, [dispatch]); var addChildComponent = useCallback(function (payload) { return dispatch({ type: 'addChild', payload: payload }); }, [dispatch]); var removeComponent = useCallback(function (payload) { return dispatch({ type: 'remove', payload: payload }); }, [dispatch]); var updateComponent = useCallback(function (payload) { return dispatch({ type: 'update', payload: payload }); }, [dispatch]); var addTemplate = useCallback(function (payload) { return dispatch({ type: 'addTemplate', payload: payload }); }, [dispatch]); var makeTemplate = useCallback(function (payload) { return dispatch({ type: 'makeTemplate', payload: payload }); }, [dispatch]); var updateState = useCallback(function (payload) { return dispatch({ type: 'updateState', payload: payload }); }, [dispatch]); var replaceState = useCallback(function (payload) { return dispatch({ type: 'replaceState', payload: payload }); }, [dispatch]); var duplicate = useCallback(function (payload) { return dispatch({ type: 'duplicate', payload: payload }); }, [dispatch]); var removeTemplate = useCallback(function (payload) { return dispatch({ type: 'removeTemplate', payload: payload }); }, [dispatch]); var applyAttributes = useCallback(function (payload) { return dispatch({ type: 'applyAttributes', payload: payload }); }, [dispatch]); var insertAsProperty = useCallback(function (payload) { return dispatch({ type: 'insertAsProperty', payload: payload }); }, [dispatch]); return { addComponent: addComponent, addChildComponent: addChildComponent, removeComponent: removeComponent, updateComponent: updateComponent, addTemplate: addTemplate, makeTemplate: makeTemplate, updateState: updateState, replaceState: replaceState, duplicate: duplicate, removeTemplate: removeTemplate, applyAttributes: applyAttributes, insertAsProperty: insertAsProperty }; }; var useSelectedComponentData = function useSelectedComponentData(selectedComponent, components) { var _useState = useState(), _useState2 = _slicedToArray(_useState, 2), selectedComponentData = _useState2[0], setSelectedComponentData = _useState2[1]; useEffect(function () { var isMounted = true; if (isMounted && selectedComponent) { var _components$all; setSelectedComponentData(components === null || components === void 0 ? void 0 : (_components$all = components.all) === null || _components$all === void 0 ? void 0 : _components$all[selectedComponent]); } return function () { return isMounted = false; }; }, [selectedComponent, components]); return [selectedComponentData, setSelectedComponentData]; }; var useTmpAttributes = function useTmpAttributes(currentlySelected) { var _useState = useState(), _useState2 = _slicedToArray(_useState, 2), tmpAttributes = _useState2[0], setTmpAttributes = _useState2[1]; // Reset tmp attributes if selection changed useEffect(function () { var isMounted = true; isMounted && setTmpAttributes(); return function () { return isMounted = false; }; }, [currentlySelected]); return [tmpAttributes, setTmpAttributes]; }; function ownKeys$J(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$J(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$J(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$J(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } var EventsProvider = function EventsProvider(_ref) { var children = _ref.children, _ref$max = _ref.max, max = _ref$max === void 0 ? 10 : _ref$max; var _useState = useState({ events: [], currentEvent: 0, isLastIgnored: false }), _useState2 = _slicedToArray(_useState, 2), state = _useState2[0], setState = _useState2[1]; var _useComponentBuilder = useComponentBuilder(), components = _useComponentBuilder.components, replaceState = _useComponentBuilder.replaceState, currentlySelected = _useComponentBuilder.currentlySelected, setCurrentlySelected = _useComponentBuilder.setCurrentlySelected, defaultSelected = _useComponentBuilder.defaultSelected; useEffect(function () { return add(components); }, [components]); var add = function add(components) { var events = state.events, isLastIgnored = state.isLastIgnored; if (isLastIgnored) { setState(function (prev) { return _objectSpread$J(_objectSpread$J({}, prev), {}, { isLastIgnored: false }); }); return; } var eventsLength = events.length; if (eventsLength >= max) { events.shift(); eventsLength = max - 1; } events.push({ components: JSON.stringify(components) }); setState({ events: events, currentEvent: eventsLength }); }; var next = function next() { var currentEvent = state.currentEvent, events = state.events; var nextEvent = currentEvent + 1; var event = events[nextEvent]; if (event && nextEvent < state.events.length) { setState(function (prev) { return _objectSpread$J(_objectSpread$J({}, prev), {}, { currentEvent: nextEvent > state.events.length ? state.events.length - 1 : nextEvent, isLastIgnored: true }); }); replaceState(JSON.parse(event.components)); } }; var undo = function undo() { var currentEvent = state.currentEvent, events = state.events; var nextEvent = currentEvent - 1; var event = events[nextEvent >= 0 ? nextEvent : 0]; if (event && currentEvent > 0) { setState(function (prev) { return _objectSpread$J(_objectSpread$J({}, prev), {}, { currentEvent: nextEvent >= 0 ? nextEvent : 0, isLastIgnored: true }); }); var newState = JSON.parse(event.components); replaceState(newState); if (!newState.all[currentlySelected.id]) setCurrentlySelected(defaultSelected); } }; useKeyPress('meta.z', function (e) { return !e.shiftKey && undo(); }); useKeyPress('ctrl.z', function (e) { return !e.shiftKey && undo(); }); useKeyPress('meta.shift.z', next); useKeyPress('ctrl.shift.z', next); return /*#__PURE__*/jsx(EventsContext.Provider, { value: {}, children: children }); }; var _TYPE_TO_NAME_MAP; var REACT_COMPONENT_TYPE = 'REACT'; var REACT_NATIVE_COMPONENT_TYPE = 'REACT_NATIVE'; var HTML_COMPONENT_TYPE = 'HTML'; var NEXT_COMPONENT_TYPE = 'NEXT'; var TYPE_TO_NAME_MAP = (_TYPE_TO_NAME_MAP = {}, _defineProperty(_TYPE_TO_NAME_MAP, REACT_COMPONENT_TYPE, 'React'), _defineProperty(_TYPE_TO_NAME_MAP, HTML_COMPONENT_TYPE, 'Html'), _defineProperty(_TYPE_TO_NAME_MAP, REACT_NATIVE_COMPONENT_TYPE, 'Native'), _defineProperty(_TYPE_TO_NAME_MAP, NEXT_COMPONENT_TYPE, 'Next'), _TYPE_TO_NAME_MAP); var PAGES = 'pages'; var GLOBAL_TEMPLATES = 'globalTemplates'; var fbConfig = { apiKey: 'AIzaSyCCZAH8CciTxougD7XSR50vaeg-hOW_omM', authDomain: 'component-builder-e0578.firebaseapp.com', projectId: 'component-builder-e0578', storageBucket: 'component-builder-e0578.appspot.com', messagingSenderId: '76905756415', appId: '1:76905756415:web:8a29058e63ada5248afeca' }; var app = initializeApp(fbConfig); var firestore = getFirestore(app); function ownKeys$I(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$I(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$I(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$I(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } var getDocData = /*#__PURE__*/function () { var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(collectionName, id) { var docRef, snap; return _regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: docRef = doc(firestore, collectionName, id); _context.next = 3; return getDoc(docRef); case 3: snap = _context.sent; return _context.abrupt("return", snap.exists() ? snap.data() : null); case 5: case "end": return _context.stop(); } } }, _callee); })); return function getDocData(_x, _x2) { return _ref.apply(this, arguments); }; }(); var create = /*#__PURE__*/function () { var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(collection, id, data) { var additionalData, _len2, args, _key2, _args3 = arguments; return _regeneratorRuntime.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: additionalData = { _updatedAt: serverTimestamp(), _createdAt: serverTimestamp() }; for (_len2 = _args3.length, args = new Array(_len2 > 3 ? _len2 - 3 : 0), _key2 = 3; _key2 < _len2; _key2++) { args[_key2 - 3] = _args3[_key2]; } _context3.next = 4; return setDoc(doc.apply(void 0, [firestore, collection, id].concat(args)), _objectSpread$I(_objectSpread$I({}, data), {}, { _id: id }, additionalData)); case 4: case "end": return _context3.stop(); } } }, _callee3); })); return function create(_x5, _x6, _x7) { return _ref3.apply(this, arguments); }; }(); var update = /*#__PURE__*/function () { var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(collection, id, data) { var ref, additionalData; return _regeneratorRuntime.wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: ref = doc(firestore, collection, id); additionalData = { _updatedAt: serverTimestamp() }; _context5.next = 4; return updateDoc(ref, _objectSpread$I(_objectSpread$I({}, data), additionalData)); case 4: case "end": return _context5.stop(); } } }, _callee5); })); return function update(_x10, _x11, _x12) { return _ref5.apply(this, arguments); }; }(); Select.Option; var _templateObject$c; styled(Box)(_templateObject$c || (_templateObject$c = _taggedTemplateLiteral(["\n display: flex;\n justify-content: center;\n align-items: center;\n cursor: pointer;\n height: var(--btn-height-base);\n padding: 0 var(--btn-padding-horizontal-base);\n border-radius: var(--ql-border-radius-md);\n color: var(--ql-color-dark-t-lighten1);\n &:hover {\n color: var(--ql-color-black);\n background: var(--ql-color-dark-t-lighten4);\n }\n ", "\n"])), function (_ref) { var active = _ref.active; return active && "color: var(--ql-color-black);\n background: var(--ql-color-dark-t-lighten4);\n font-weight: 600;"; }); function ownKeys$H(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$H(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$H(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$H(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } var ALL = 'ALL'; _objectSpread$H(_defineProperty({}, ALL, 'All'), TYPE_TO_NAME_MAP); var ComponentTypeContext = /*#__PURE__*/createContext(); var ComponentTypeProvider = function ComponentTypeProvider(_ref) { var children = _ref.children, initialComponentType = _ref.initialComponentType; var _useState = useState(initialComponentType || NEXT_COMPONENT_TYPE), _useState2 = _slicedToArray(_useState, 2), componentType = _useState2[0], setComponentType = _useState2[1]; return /*#__PURE__*/jsx(ComponentTypeContext.Provider, { value: { componentType: componentType, setComponentType: setComponentType }, children: children }); }; var LiveSaveContext = /*#__PURE__*/createContext(); /** * It takes a component, and recursively parses its children, and then parses the attributes of the * component * @param all - The entire collection of components. * @param id - The id of the component to parse. * @param parentId - The id of the parent component. * @param [withTransform=false] - Object must be returned instead id * @param [withIdReplace=false] - If true, the old id will be replaced with a new id. * @param [withIdRemove=false] - If true, the component's id and parentId will be removed. * @param components - Object ref for setting list of new components * @returns The id of the component. */ var parseChild = function parseChild(params) { var _component$children; var all = params.all, id = params.id, parentId = params.parentId, _params$withTransform = params.withTransform, withTransform = _params$withTransform === void 0 ? false : _params$withTransform, _params$withIdReplace = params.withIdReplace, withIdReplace = _params$withIdReplace === void 0 ? false : _params$withIdReplace, _params$withIdRemove = params.withIdRemove, withIdRemove = _params$withIdRemove === void 0 ? false : _params$withIdRemove, components = params.components; var component = JSON.parse(JSON.stringify(all[id])); var componentId = withIdReplace ? nanoid() : component.id; // Transforming children into deep ds component.children = ((_component$children = component.children) === null || _component$children === void 0 ? void 0 : _component$children.map(function (_id) { return parseChild({ all: all, id: _id, parentId: componentId, withIdReplace: withIdReplace, withTransform: withTransform, withIdRemove: withIdRemove, components: components }); })) || []; // Transforming attributes into deep ds component.attributes = parseAttributes({ attributes: component === null || component === void 0 ? void 0 : component.attributes, all: all, parentId: componentId, withIdReplace: withIdReplace, withTransform: withTransform, withIdRemove: withIdRemove, components: components }); component.id = componentId; if (parentId) component.parentId = parentId; if (components) components[componentId] = component; if (withIdRemove) { delete component.id; delete component.parentId; } return withTransform ? component : componentId; }; function ownKeys$G(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$G(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$G(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$G(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } /** * It takes the attributes of a component and parses them into an object * @param attributes - The attributes of the current node. * @param parentId - The id of the parent element. * @param all - The entire tree of components. * @param [withTransform=false] - If true, the attribute will be transformed into a component. * @param [withIdReplace=false] - If true, the id of the parent component will be replaced with the id * of the child component. * @param [withIdRemove=false] - If true, the id of the component will be removed from the attributes. * @param components - The components object that contains all the components. * @returns The parsed attributes. */ var parseAttributes = function parseAttributes(params) { var attributes = params.attributes, parentId = params.parentId, all = params.all, _params$withTransform = params.withTransform, withTransform = _params$withTransform === void 0 ? false : _params$withTransform, _params$withIdReplace = params.withIdReplace, withIdReplace = _params$withIdReplace === void 0 ? false : _params$withIdReplace, _params$withIdRemove = params.withIdRemove, withIdRemove = _params$withIdRemove === void 0 ? false : _params$withIdRemove, components = params.components; var parsedAttributes = Object.keys(attributes || {}).reduce(function (acc, key) { var attribute = attributes[key]; var isComponent = (attribute === null || attribute === void 0 ? void 0 : attribute.type) === 'component'; // Parsing attribute with possibility to convert into component(object) or id(string) if (isComponent) { var _attribute = parseChild({ id: attribute.value, parentId: parentId, all: all, withIdReplace: withIdReplace, withTransform: withTransform, withIdRemove: withIdRemove, components: components }); return _objectSpread$G(_objectSpread$G({}, acc), {}, _defineProperty({}, key, { type: 'component', value: _attribute })); } return _objectSpread$G(_objectSpread$G({}, acc), {}, _defineProperty({}, key, attribute)); }, {}); return parsedAttributes; }; function ownKeys$F(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$F(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$F(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$F(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } /** * It takes an id and a structure, and returns a structure with the same id, but with the children * transformed into a deep structure * @param id - The id of the component you want to parse * @param all - The entire structure of the component tree. * @param [additionalData] - This is an object that can be used to pass additional data to the * template. * @returns A structure that is ready to be used in the template. */ var parseStructureForTemplate = function parseStructureForTemplate(id, all) { var _component$children; var additionalData = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var _component = _objectSpread$F({}, all[id]); delete _component.id; _component.parentId = 'root'; // Transforming children into deep ds _component.children = ((_component$children = _component.children) === null || _component$children === void 0 ? void 0 : _component$children.map(function (key) { return parseChild({ id: key, all: all, withIdRemove: true, withTransform: true }); })) || []; _component.attributes = parseAttributes({ attributes: _component.attributes, all: all, withIdRemove: true, withTransform: true }) || {}; return _objectSpread$F(_objectSpread$F({}, _component), additionalData); }; function ownKeys$E(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$E(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$E(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$E(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } /** * It takes a component's id and all of the components, and returns a component with its children * parsed * @param id - The id of the component you want to parse. * @param all - The entire structure of the components. * @returns A component with its children parsed. */ var parseStructure = function parseStructure(id, all) { var _component$children; var _component = _objectSpread$E({}, all[id]); // Transforming children into deep ds _component.children = ((_component$children = _component.children) === null || _component$children === void 0 ? void 0 : _component$children.map(function (key) { return parseChild({ id: key, all: all, withTransform: true }); })) || []; _component.attributes = parseAttributes({ attributes: _component.attributes, all: all, withTransform: true }) || {}; return _objectSpread$E({}, _component); }; function ownKeys$D(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$D(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$D(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$D(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } /** * It takes the structure of the page and the id of the component to be copied. It parses the structure * of the page and returns a new structure with the copied component * @param _all - The entire structure of the project. * @param id - The id of the component to be copied. * @returns A list of two items: * 1. A dictionary of components, where the key is the component id and the value is the component * object. * 2. The component object that was parsed. */ var parseForCopyAndDuplicate = function parseForCopyAndDuplicate(_all, id) { var all = JSON.parse(JSON.stringify(_all)); var components = {}; var parseStructure = function parseStructure(_id) { var _component = _objectSpread$D({}, all[_id]); var componentId = nanoid(); _component.id = componentId; // Transforming children into deep ds _component.children = _component.children.map(function (el) { return parseChild({ id: el, all: all, parentId: componentId, withIdReplace: true, components: components }); }); _component.attributes = parseAttributes({ attributes: _component.attributes, all: all, parentId: componentId, withIdReplace: true, components: components }) || {}; components[componentId] = _component; return [components, _component]; }; return parseStructure(id); }; var NUMBER_OF_ACTIONS_TO_AUTOSAVE = 3; var LiveSaveProvider = function LiveSaveProvider(props) { var children = props.children, onChange = props.onChange, _props$numberOfAction = props.numberOfActionsBeforeAutoSave, numberOfActionsBeforeAutoSave = _props$numberOfAction === void 0 ? NUMBER_OF_ACTIONS_TO_AUTOSAVE : _props$numberOfAction; var _useState = useState(false), _useState2 = _slicedToArray(_useState, 2), textVisibility = _useState2[0], setTextVisibility = _useState2[1]; // State to monitor how many changes were made and trigger autosave // depending on actions limit number var _useState3 = useState(0), _useState4 = _slicedToArray(_useState3, 2), currentNumberOfActions = _useState4[0], setCurrentNumberOfActions = _useState4[1]; var _useComponentBuilder = useComponentBuilder(), components = _useComponentBuilder.components, isTemplateEditPage = _useComponentBuilder.isTemplateEditPage, defaultSelected = _useComponentBuilder.defaultSelected; var saveTemplate = function saveTemplate() { var template = parseStructureForTemplate(defaultSelected.id, components.all); onChange === null || onChange === void 0 ? void 0 : onChange(template); }; var savePage = function savePage() { return onChange === null || onChange === void 0 ? void 0 : onChange(components); }; var saveChanges = /*#__PURE__*/function () { var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(e) { return _regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: e === null || e === void 0 ? void 0 : e.preventDefault(); _context.prev = 1; _context.next = 4; return isTemplateEditPage ? saveTemplate() : savePage(); case 4: setTextVisibility(true); _context.next = 10; break; case 7: _context.prev = 7; _context.t0 = _context["catch"](1); console.error('Error during save', JSON.stringify(_context.t0)); case 10: case "end": return _context.stop(); } } }, _callee, null, [[1, 7]]); })); return function saveChanges(_x) { return _ref.apply(this, arguments); }; }(); useEffect(function () { var isMounted = true; if (isMounted && currentNumberOfActions === numberOfActionsBeforeAutoSave) { saveChanges(); setCurrentNumberOfActions(0); } else isMounted && setCurrentNumberOfActions(function (prev) { return prev + 1; }); return function () { return isMounted = false; }; }, [components, numberOfActionsBeforeAutoSave]); useEffect(function () { textVisibility && setTimeout(function () { return setTextVisibility(false); }, 3000); }, [textVisibility]); return /*#__PURE__*/jsx(LiveSaveContext.Provider, { value: { saveChanges: saveChanges, textVisibility: textVisibility }, children: children }); }; var ResponsiveContext = /*#__PURE__*/createContext(); //get all styles from qonsoll after component mount function getStyles() { var css = []; for (var i = 0; i < document.styleSheets.length; i++) { var sheet = document.styleSheets[i]; var rules = 'cssRules' in sheet ? sheet.cssRules : sheet.rules; if (rules) { css.push('\n/* Stylesheet : ' + (sheet.href || '[inline styles]') + ' */'); for (var j = 0; j < rules.length; j++) { var rule = rules[j]; if ('cssText' in rule) css.push(rule.cssText);else css.push(rule.selectorText + ' {\n' + rule.style.cssText + '\n}\n'); } } } return css.join('\n') + '\n'; } var sortByDate = function sortByDate(list, order) { return list ? _.orderBy(list, ['_createdAt'], [order || 'desc']) : []; }; var ResponsiveProvider = function ResponsiveProvider(_ref) { var _parentRef$current, _parentRef$current2; var children = _ref.children, parentRef = _ref.parentRef; var _useState = useState(false), _useState2 = _slicedToArray(_useState, 2), isResponseOn = _useState2[0], setIsResponseOn = _useState2[1]; var _useState3 = useState(null), _useState4 = _slicedToArray(_useState3, 2), currentStyle = _useState4[0], setCurrentStyle = _useState4[1]; var _useState5 = useState(), _useState6 = _slicedToArray(_useState5, 2), wrapperHeight = _useState6[0], setWrapperHeight = _useState6[1]; var _useState7 = useState(), _useState8 = _slicedToArray(_useState7, 2), wrapperWidth = _useState8[0], setWrapperWidth = _useState8[1]; var _useState9 = useState(1), _useState10 = _slicedToArray(_useState9, 2), scaleNum = _useState10[0], setScaleNum = _useState10[1]; var _useState11 = useState(null), _useState12 = _slicedToArray(_useState11, 2), node = _useState12[0], setNode = _useState12[1]; var wrapperRef = useRef(); var iframeRef = useRef(); var parentWidth = parentRef === null || parentRef === void 0 ? void 0 : (_parentRef$current = parentRef.current) === null || _parentRef$current === void 0 ? void 0 : _parentRef$current.clientWidth; var parentHeight = parentRef === null || parentRef === void 0 ? void 0 : (_parentRef$current2 = parentRef.current) === null || _parentRef$current2 === void 0 ? void 0 : _parentRef$current2.clientHeight; useEffect(function () { var isMounted = true; if (isMounted) { if (wrapperRef) setNode(wrapperRef.current); checkBlockOverLimit(); setCurrentStyle(isResponseOn ? getStyles() : ''); } return function () { return isMounted = false; }; }, [isResponseOn, wrapperHeight, wrapperWidth]); var handleSizeChange = function handleSizeChange(w, h) { setWrapperHeight(h); setWrapperWidth(w); checkBlockOverLimit(); setCurrentStyle(getStyles()); setIsResponseOn(true); }; //Check or iFrame size isn't bigger than window size/ In case if is - scale iframe content to fit var checkBlockOverLimit = function checkBlockOverLimit() { if (wrapperWidth > parentWidth) { setScaleNum(parentWidth / wrapperWidth); } else if (wrapperWidth < parentWidth + 1) { setScaleNum(1); } else return 1; }; var frameWidthLimit = function frameWidthLimit() { if (wrapperWidth > parentWidth - 10) return '100%';else return wrapperWidth; }; var frameHeightLimit = function frameHeightLimit() { if (wrapperHeight > parentHeight - 10) return parentHeight;else return wrapperHeight; }; return /*#__PURE__*/jsx(ResponsiveContext.Provider, { value: { isResponseOn: isResponseOn, setIsResponseOn: setIsResponseOn, getStyles: getStyles, currentStyle: currentStyle, setCurrentStyle: setCurrentStyle, wrapperHeight: wrapperHeight, setWrapperHeight: setWrapperHeight, wrapperWidth: wrapperWidth, setWrapperWidth: setWrapperWidth, scaleNum: scaleNum, setScaleNum: setScaleNum, handleSizeChange: handleSizeChange, node: node, wrapperRef: wrapperRef, iframeRef: iframeRef, parentHeight: parentHeight, parentWidth: parentWidth, frameWidthLimit: frameWidthLimit, frameHeightLimit: frameHeightLimit }, children: children }); }; var AdditionalPropsContext = /*#__PURE__*/createContext(); function ownKeys$C(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$C(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$C(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$C(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } var AdditionalPropsProvider = function AdditionalPropsProvider(props) { var children = props.children, _props$components = props.components, components = _props$components === void 0 ? {} : _props$components, _props$variables = props.variables, variables = _props$variables === void 0 ? {} : _props$variables; var providerValue = useMemo(function () { return _objectSpread$C({ variables: _objectSpread$C({}, variables) }, components); }, [variables, components]); return /*#__PURE__*/jsx(AdditionalPropsContext.Provider, { value: providerValue, children: children }); }; AdditionalPropsProvider.propTypes = { children: PropTypes.any, components: PropTypes.shape({ Asq: PropTypes.shape({ forms: PropTypes.array, onFinish: PropTypes.func, getForm: PropTypes.func, getFormQuestions: PropTypes.func }), Video: PropTypes.shape({ videos: PropTypes.array }) }), variables: PropTypes.any }; var useAdditionalProps = function useAdditionalProps() { return useContext(AdditionalPropsContext); }; var useExtractAdditionalProps = function useExtractAdditionalProps(name) { var context = useContext(AdditionalPropsContext) || {}; var additionalProps = useMemo(function () { var _context$hasOwnProper; return context !== null && context !== void 0 && (_context$hasOwnProper = context.hasOwnProperty) !== null && _context$hasOwnProper !== void 0 && _context$hasOwnProper.call(context, name) ? context[name] : {}; }, [name, context]); return additionalProps; }; var useLayout = function useLayout() { return useContext(LayotContext) || {}; }; var useComponentType = function useComponentType() { return useContext(ComponentTypeContext); }; var useLiveSave = function useLiveSave() { return useContext(LiveSaveContext); }; var useResponsive = function useResponsive() { return useContext(ResponsiveContext); }; function ownKeys$B(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$B(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$B(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$B(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } var UniversalComponentList = function UniversalComponentList(props) { var innerElements = props.innerElements, parentId = props.parentId; var _useComponentBuilder = useComponentBuilder(), components = _useComponentBuilder.components; return !!innerElements.length ? /*#__PURE__*/jsx(Fragment, { children: innerElements.map(function (childrenId) { var data = components.all[childrenId]; var ucProps = { key: childrenId, parentId: parentId, data: data }; return /*#__PURE__*/jsx(UniversalComponent$1, _objectSpread$B({}, ucProps)); }) }) : null; }; var UniversalComponentsList = /*#__PURE__*/memo(UniversalComponentList); var generateSpaces = function generateSpaces(count) { var tabSize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2; return Array(count * tabSize).fill(' ').join(''); }; var getName = function getName(title) { return title.split('').map(function (el, index) { return !index ? el.toUpperCase() : el; }).map(function (el, index) { return title[index - 1] === ' ' ? el.toUpperCase() : el; }).join('').replaceAll(' ', ''); }; var generateAttributes = function generateAttributes(attributes) { return attributes ? Object.keys(attributes).map(function (attr) { var attrValue = "".concat(attributes[attr]); var isBoolean = !![true, false, 'true', 'false'].includes(attrValue); return " ".concat(attr, "=").concat(isBoolean ? "{".concat(attrValue, "}") : "\"".concat(attrValue, "\"")); }).join('') : ''; }; var ReactTemplate = "{{#each imports}}import { {{elements}} } from '{{lib}}'\n{{/each}}\n{{#if states}}import { useState } from 'React'\n{{/if}}\n\nfunction {{componentName}}(props) {\n{{#each states as |state|}} const [{{state}}, set{{capitalize state}}] = useState()\n{{/each}}{{#if states}}\n{{/if}}\n return (\n <>\n{{code}}\n </>\n )\n}\n\nexport default {{componentName}}\n"; var useReactComponentBuilder = function useReactComponentBuilder() { var _useComponentBuilder = useComponentBuilder(), components = _useComponentBuilder.components, isTemplateEditPage = _useComponentBuilder.isTemplateEditPage; var all = components.all; var parseBody = function parseBody(components, lib, folder) { var _imports; /* imports => { "@qonsoll...": ['Container', 'Row', ...], ... } */ var imports = (_imports = {}, _defineProperty(_imports, lib, []), _defineProperty(_imports, folder, []), _imports); var mappingItem = function mappingItem(data, level) { var name = data.name, _children = data.children, _text = data.text, attributes = data.attributes; var spaces = generateSpaces(level + 1); var spacesForChildren = generateSpaces(level + 2); var attrs = generateAttributes(attributes); var text = _text ? spacesForChildren + _text : ''; var children = text + (_children && deepParse(_children, level + 1)); var componentCode = children ? "".concat(spaces, "<").concat(name).concat(attrs, ">\n").concat(children, "\n").concat(spaces, "</").concat(name, ">") : "".concat(spaces, "<").concat(name).concat(attrs, " />"); return componentCode; }; /* recursive function */ var deepParse = function deepParse(components /*ids*/ ) { var level = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2; components.forEach(function (_ref) { var name = _ref.name, _lib = _ref.lib; !imports[_lib || lib].includes(name) && imports[_lib || lib].push(name); }); return "".concat(components.map(function (data) { return mappingItem(data, level); }).join('\n')); }; /* recursive function */ var code = deepParse(components); // Formating imports for hbs var importsFormated = Object.keys(imports).map(function (key) { return { lib: key, elements: imports[key].join(', ') }; }).filter(function (_ref2) { var elements = _ref2.elements; return !!(elements !== null && elements !== void 0 && elements.length); }); return [code, importsFormated]; }; var genCompCode = function genCompCode(list, lib, folder) { var name = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'Component'; var _parseBody = parseBody(list, lib, folder), _parseBody2 = _slicedToArray(_parseBody, 2), _code = _parseBody2[0], imports = _parseBody2[1]; var data = { imports: imports, componentName: name, code: _code, lib: lib }; return Handlebars.compile(ReactTemplate)(data); }; var exportComponent = function exportComponent(componentsIds, lib) { var folder = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : './components'; var componentsToExport = []; var components = componentsIds.map(function (el) { return parseStructure(el, all); }); var templatesParse = function templatesParse(components) { return components.map(function (componentData) { var _componentData$childr; var templateName = componentData.templateName, title = componentData.title, name = componentData.name; if (!!((_componentData$childr = componentData.children) !== null && _componentData$childr !== void 0 && _componentData$childr.length)) componentData.children = templatesParse(componentData.children); // Workaround for template edit to not import unnecessary components as templates if (templateName && !isTemplateEditPage) { var data = { name: getName(title || name), children: [], lib: folder }; componentsToExport.push({ components: [componentData], name: getName(title || name) }); return data; } return componentData; }); }; componentsToExport.push({ components: templatesParse(components) }); return componentsToExport.map(function (_ref3) { var components = _ref3.components, name = _ref3.name; return genCompCode(components, lib, folder, name); }).join('\n================================================\n\n'); }; return { exportComponent: exportComponent }; }; var useStateParser = function useStateParser() { var _useComponentBuilder = useComponentBuilder(), components = _useComponentBuilder.components; var _useReactComponentBui = useReactComponentBuilder(), exportReactComponent = _useReactComponentBui.exportComponent; // const { generateComponent: generateHtmlComponent } = useHtmlComponentBuilder() var parse = function parse(type) { var _typeToParserMap; var state = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : components === null || components === void 0 ? void 0 : components.root; var typeToParserMap = (_typeToParserMap = {}, _defineProperty(_typeToParserMap, REACT_NATIVE_COMPONENT_TYPE, reactNativeParser), _defineProperty(_typeToParserMap, REACT_COMPONENT_TYPE, reactParser), _defineProperty(_typeToParserMap, HTML_COMPONENT_TYPE, htmlParser), _defineProperty(_typeToParserMap, NEXT_COMPONENT_TYPE, nextParser), _typeToParserMap); var componentsIds = state.map(function (_ref) { var id = _ref.id; return id; }); return typeToParserMap[type](componentsIds); }; var reactParser = function reactParser(componentsIds) { return exportReactComponent(componentsIds, '@qonsoll/react-design'); }; var htmlParser = function htmlParser(componentsIds) {// return generateHtmlComponent(componentsIds) }; var reactNativeParser = function reactNativeParser(componentsIds) {}; var nextParser = function nextParser(componentsIds) { return exportReactComponent(componentsIds, '@qonsoll/qonstructor-next-components'); }; return { parse: parse }; }; var _typeToLibraryMap; var typeToLibraryMap = (_typeToLibraryMap = {}, _defineProperty(_typeToLibraryMap, REACT_COMPONENT_TYPE, ReactLibElements), _defineProperty(_typeToLibraryMap, NEXT_COMPONENT_TYPE, NextLibElements), _typeToLibraryMap); var useExtractComponent = function useExtractComponent(type, name) { var library = useMemo(function () { return typeToLibraryMap[type]; }, [type]); var Component = useMemo(function () { return library && name ? library[name] : null; }, [library, name]); return Component; }; function ownKeys$A(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$A(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$A(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$A(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } var useTransformInitialValues = function useTransformInitialValues(initialData, globalTemplates) { var transform = useCallback(function (data, templates) { var _templates$filter; var _componentType = data === null || data === void 0 ? void 0 : data.componentType; var _templates = (templates === null || templates === void 0 ? void 0 : (_templates$filter = templates.filter(function (elem) { return (elem === null || elem === void 0 ? void 0 : elem.componentType) === _componentType