Socket
Socket
Sign inDemoInstall

@craftjs/utils

Package Overview
Dependencies
Maintainers
1
Versions
74
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@craftjs/utils - npm Package Compare versions

Comparing version 0.1.0-beta.13 to 0.2.0-alpha.0

603

dist/cjs/index.js

@@ -1,1 +0,602 @@

"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var produce=require("immer"),isEqualWith=require("lodash.isequalwith"),React=require("react"),invariant=require("tiny-invariant");function _interopDefaultLegacy(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var produce__default=_interopDefaultLegacy(produce),isEqualWith__default=_interopDefaultLegacy(isEqualWith),React__default=_interopDefaultLegacy(React),invariant__default=_interopDefaultLegacy(invariant),ROOT_NODE="ROOT",DEPRECATED_ROOT_NODE="canvas-ROOT",ERROR_NOPARENT="Parent id cannot be ommited",ERROR_DUPLICATE_NODEID="Attempting to add a node with duplicated id",ERROR_INVALID_NODEID="Node does not exist, it may have been removed",ERROR_TOP_LEVEL_ELEMENT_NO_ID='A <Element /> that is used inside a User Component must specify an `id` prop, eg: <Element id="text_element">...</Element> ',ERROR_MISSING_PLACEHOLDER_PLACEMENT="Placeholder required placement info (parent, index, or where) is missing",ERROR_MOVE_CANNOT_DROP="Node cannot be dropped into target parent",ERROR_MOVE_INCOMING_PARENT="Target parent rejects incoming node",ERROR_MOVE_OUTGOING_PARENT="Current parent rejects outgoing node",ERROR_MOVE_NONCANVAS_CHILD="Cannot move node that is not a direct child of a Canvas node",ERROR_MOVE_TO_NONCANVAS_PARENT="Cannot move node into a non-Canvas parent",ERROR_MOVE_TOP_LEVEL_NODE="A top-level Node cannot be moved",ERROR_MOVE_ROOT_NODE="Root Node cannot be moved",ERROR_MOVE_TO_DESCENDANT="Cannot move node into a descendant",ERROR_NOT_IN_RESOLVER="The component type specified for this node does not exist in the resolver",ERROR_INFINITE_CANVAS="The component specified in the <Canvas> `is` prop has additional Canvas specified in it's render template.",ERROR_CANNOT_DRAG="The node has specified a canDrag() rule that prevents it from being dragged",ERROR_INVALID_NODE_ID="Invalid parameter Node Id specified",ERROR_DELETE_TOP_LEVEL_NODE="Attempting to delete a top-level Node",ERROR_RESOLVER_NOT_AN_OBJECT="Resolver in <Editor /> has to be an object. For (de)serialization Craft.js needs a list of all the User Components. \n \nMore info: https://craft.js.org/r/docs/api/editor#props",ERROR_DESERIALIZE_COMPONENT_NOT_IN_RESOLVER="An Error occurred while deserializing components: Cannot find component <%displayName% /> in resolver map. Please check your resolver in <Editor />\n\nAvailable components in resolver: %availableComponents%\n\nMore info: https://craft.js.org/r/docs/api/editor#props",_assign=function(){return(_assign=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e}).apply(this,arguments)};function __spreadArrays(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;var r=Array(e),o=0;for(t=0;t<n;t++)for(var i=arguments[t],a=0,s=i.length;a<s;a++,o++)r[o]=i[a];return r}var HISTORY_ACTIONS={UNDO:"HISTORY_UNDO",REDO:"HISTORY_REDO",THROTTLE:"HISTORY_THROTTLE",IGNORE:"HISTORY_IGNORE"},History=function(){function e(){this.timeline=[],this.pointer=-1}return e.prototype.add=function(e,t){0===e.length&&0===t.length||(this.pointer=this.pointer+1,this.timeline.length=this.pointer,this.timeline[this.pointer]={patches:e,inversePatches:t,timestamp:Date.now()})},e.prototype.throttleAdd=function(e,t,n){if(void 0===n&&(n=500),0!==e.length||0!==t.length){if(this.timeline.length&&this.pointer>=0){var r=this.timeline[this.pointer],o=r.patches,i=r.timestamp;if((new Date).getTime()-i<n&&o.length===e.length&&o.every((function(t,n){var r=e[n];return r.op===t.op&&isEqualWith__default.default(r.path,t.path)})))return void(this.throttledInversePatch||(this.throttledInversePatch=t))}this.add(e,this.throttledInversePatch||t),this.throttledInversePatch=null}},e.prototype.canUndo=function(){return this.pointer>=0},e.prototype.canRedo=function(){return this.pointer<this.timeline.length-1},e.prototype.undo=function(e){if(this.canUndo()){this.throttledInversePatch=null;var t=this.timeline[this.pointer].inversePatches;return this.pointer=this.pointer-1,produce.applyPatches(e,t)}},e.prototype.redo=function(e){if(this.canRedo())return this.pointer=this.pointer+1,produce.applyPatches(e,this.timeline[this.pointer].patches)},e}();function useMethods(e,t,n,r){var o,i=React.useMemo((function(){return new History}),[]),a=React.useRef([]),s=React.useRef();"function"==typeof e?o=e:(o=e.methods,a.current=e.ignoreHistoryForActions,s.current=e.normalizeHistory);var c=React.useRef(r);c.current=r;var R=React.useMemo((function(){var e=s.current,t=a.current,r=c.current;return[function(a,s){var c,R=n&&createQuery(n,(function(){return a}),i),u=produce.produceWithPatches(a,(function(e){var t,n;switch(s.type){case HISTORY_ACTIONS.UNDO:return i.undo(e);case HISTORY_ACTIONS.REDO:return i.redo(e);case HISTORY_ACTIONS.IGNORE:case HISTORY_ACTIONS.THROTTLE:var r=s.payload,a=r[0],c=r.slice(1);(t=o(e,R))[a].apply(t,c);break;default:(n=o(e,R))[s.type].apply(n,s.payload)}})),O=u[0],E=u[1],_=u[2];return c=O,r&&r(O,a,{type:s.type,params:s.payload,patches:E},R,(function(e){var t=produce.produceWithPatches(O,e);c=t[0],E=__spreadArrays(E,t[1]),_=__spreadArrays(t[2],_)})),[HISTORY_ACTIONS.UNDO,HISTORY_ACTIONS.REDO].includes(s.type)&&e&&(c=produce__default.default(c,e)),__spreadArrays(t,[HISTORY_ACTIONS.UNDO,HISTORY_ACTIONS.REDO,HISTORY_ACTIONS.IGNORE]).includes(s.type)||(s.type===HISTORY_ACTIONS.THROTTLE?i.throttleAdd(E,_,s.config&&s.config.rate):i.add(E,_)),c},o]}),[i,o,n]),u=R[1],O=React.useReducer(R[0],t),E=O[0],_=O[1],p=React.useRef();p.current=E;var d=React.useMemo((function(){return n?createQuery(n,(function(){return p.current}),i):[]}),[i,n]),l=React.useMemo((function(){var e=Object.keys(u(null,null)),t=a.current;return _assign(_assign({},e.reduce((function(e,t){return e[t]=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return _({type:t,payload:e})},e}),{})),{history:{undo:function(){return _({type:HISTORY_ACTIONS.UNDO})},redo:function(){return _({type:HISTORY_ACTIONS.REDO})},throttle:function(n){return _assign({},e.filter((function(e){return!t.includes(e)})).reduce((function(e,t){return e[t]=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return _({type:HISTORY_ACTIONS.THROTTLE,payload:__spreadArrays([t],e),config:{rate:n}})},e}),{}))},ignore:function(){return _assign({},e.filter((function(e){return!t.includes(e)})).reduce((function(e,t){return e[t]=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return _({type:HISTORY_ACTIONS.IGNORE,payload:__spreadArrays([t],e)})},e}),{}))}}})}),[u]),f=React.useCallback((function(){return p.current}),[]),h=React.useMemo((function(){return new Watcher(f)}),[f]);return React.useEffect((function(){p.current=E,h.notify()}),[E,h]),React.useMemo((function(){return{getState:f,subscribe:function(e,t,n){return h.subscribe(e,t,n)},actions:l,query:d,history:i}}),[l,d,h,f,i])}function createQuery(e,t,n){var r=Object.keys(e()).reduce((function(n,r){var o;return _assign(_assign({},n),((o={})[r]=function(){for(var n,o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];return(n=e(t()))[r].apply(n,o)},o))}),{});return _assign(_assign({},r),{history:{canUndo:function(){return n.canUndo()},canRedo:function(){return n.canRedo()}}})}var Watcher=function(){function e(e){this.subscribers=[],this.getState=e}return e.prototype.subscribe=function(e,t,n){var r=this,o=new Subscriber((function(){return e(r.getState())}),t,n);return this.subscribers.push(o),this.unsubscribe.bind(this,o)},e.prototype.unsubscribe=function(e){if(this.subscribers.length){var t=this.subscribers.indexOf(e);if(t>-1)return this.subscribers.splice(t,1)}},e.prototype.notify=function(){this.subscribers.forEach((function(e){return e.collect()}))},e}(),Subscriber=function(){function e(e,t,n){void 0===n&&(n=!1),this.collector=e,this.onChange=t,n&&this.collect()}return e.prototype.collect=function(){try{var e=this.collector();isEqualWith__default.default(e,this.collected)||(this.collected=e,this.onChange&&this.onChange(this.collected))}catch(e){console.warn(e)}},e}(),getDOMPadding=function(e){return{left:parseInt(window.getComputedStyle(e).paddingLeft),right:parseInt(window.getComputedStyle(e).paddingRight),bottom:parseInt(window.getComputedStyle(e).paddingTop),top:parseInt(window.getComputedStyle(e).paddingBottom)}},getDOMMargin=function(e){return{left:parseInt(window.getComputedStyle(e).marginLeft),right:parseInt(window.getComputedStyle(e).marginRight),bottom:parseInt(window.getComputedStyle(e).marginTop),top:parseInt(window.getComputedStyle(e).marginBottom)}},getDOMInfo=function(e){var t=e.getBoundingClientRect(),n=t.x,r=t.y,o=t.top,i=t.left,a=t.bottom,s=t.right,c=t.width,R=t.height,u=getDOMMargin(e),O=getDOMPadding(e);return{x:Math.round(n),y:Math.round(r),top:Math.round(o),left:Math.round(i),bottom:Math.round(a),right:Math.round(s),width:Math.round(c),height:Math.round(R),outerWidth:Math.round(c+u.left+u.right),outerHeight:Math.round(R+u.top+u.bottom),margin:u,padding:O,inFlow:e&&e.parentElement&&!!styleInFlow(e,e.parentElement)}},getComputedStyle=function(e){return window.getComputedStyle(e)},styleInFlow=function(e,t){var n=getComputedStyle(e),r=getComputedStyle(t);if(!(n.overflow&&"visible"!==n.overflow||"none"!==r.float||t&&"flex"===r.display&&"column"!==r["flex-direction"])){switch(n.position){case"static":case"relative":break;default:return}switch(e.tagName){case"TR":case"TBODY":case"THEAD":case"TFOOT":return!0}switch(n.display){case"block":case"list-item":case"table":case"flex":return!0}}};function useCollector(e,t){var n=e.subscribe,r=e.getState,o=e.actions,i=e.query,a=React.useRef(!0),s=React.useRef(null),c=React.useRef(t);c.current=t;var R=React.useCallback((function(e){return _assign(_assign({},e),{actions:o,query:i})}),[o,i]);a.current&&t&&(s.current=t(r(),i),a.current=!1);var u=React.useState(R(s.current)),O=u[0],E=u[1];return React.useEffect((function(){var e;return c.current&&(e=n((function(e){return c.current(e,i)}),(function(e){E(R(e))}))),function(){e&&e()}}),[R,i,n]),O}function setRef(e,t){t&&("function"==typeof e?e(t):e.current=t)}function cloneWithRef(e,t){var n=e.ref;return invariant__default.default("string"!=typeof n,"Cannot connect to an element with an existing string ref. Please convert it to use a callback ref instead, or wrap it into a <span> or <div>. Read more: https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute"),React.cloneElement(e,n?{ref:function(e){setRef(n,e),setRef(t,e)}}:{ref:t})}function throwIfCompositeComponentElement(e){if("string"!=typeof e.type)throw new Error}function wrapHookToRecognizeElement(e){return function(t,n){if(void 0===t&&(t=null),!React.isValidElement(t)){var r=t;return r&&e(r,n),r}var o=t;return throwIfCompositeComponentElement(o),cloneWithRef(o,e)}}var RenderIndicator=function(e){return React__default.default.createElement("div",{style:_assign({position:"fixed",display:"block",opacity:1,borderStyle:"solid",borderWidth:"1px",borderColor:"transparent",zIndex:99999},e.style)})},useEffectOnce=function(e){React.useEffect(e,[])},deprecationWarning=function(e,t){var n="Deprecation warning: "+e+" will be deprecated in future relases.",r=t.suggest,o=t.doc;r&&(n+=" Please use "+r+" instead."),o&&(n+="("+o+")"),console.warn(n)};exports.DEPRECATED_ROOT_NODE=DEPRECATED_ROOT_NODE,exports.ERROR_CANNOT_DRAG=ERROR_CANNOT_DRAG,exports.ERROR_DELETE_TOP_LEVEL_NODE=ERROR_DELETE_TOP_LEVEL_NODE,exports.ERROR_DESERIALIZE_COMPONENT_NOT_IN_RESOLVER=ERROR_DESERIALIZE_COMPONENT_NOT_IN_RESOLVER,exports.ERROR_DUPLICATE_NODEID=ERROR_DUPLICATE_NODEID,exports.ERROR_INFINITE_CANVAS=ERROR_INFINITE_CANVAS,exports.ERROR_INVALID_NODEID=ERROR_INVALID_NODEID,exports.ERROR_INVALID_NODE_ID=ERROR_INVALID_NODE_ID,exports.ERROR_MISSING_PLACEHOLDER_PLACEMENT=ERROR_MISSING_PLACEHOLDER_PLACEMENT,exports.ERROR_MOVE_CANNOT_DROP=ERROR_MOVE_CANNOT_DROP,exports.ERROR_MOVE_INCOMING_PARENT=ERROR_MOVE_INCOMING_PARENT,exports.ERROR_MOVE_NONCANVAS_CHILD=ERROR_MOVE_NONCANVAS_CHILD,exports.ERROR_MOVE_OUTGOING_PARENT=ERROR_MOVE_OUTGOING_PARENT,exports.ERROR_MOVE_ROOT_NODE=ERROR_MOVE_ROOT_NODE,exports.ERROR_MOVE_TOP_LEVEL_NODE=ERROR_MOVE_TOP_LEVEL_NODE,exports.ERROR_MOVE_TO_DESCENDANT=ERROR_MOVE_TO_DESCENDANT,exports.ERROR_MOVE_TO_NONCANVAS_PARENT=ERROR_MOVE_TO_NONCANVAS_PARENT,exports.ERROR_NOPARENT=ERROR_NOPARENT,exports.ERROR_NOT_IN_RESOLVER=ERROR_NOT_IN_RESOLVER,exports.ERROR_RESOLVER_NOT_AN_OBJECT=ERROR_RESOLVER_NOT_AN_OBJECT,exports.ERROR_TOP_LEVEL_ELEMENT_NO_ID=ERROR_TOP_LEVEL_ELEMENT_NO_ID,exports.HISTORY_ACTIONS=HISTORY_ACTIONS,exports.History=History,exports.ROOT_NODE=ROOT_NODE,exports.RenderIndicator=RenderIndicator,exports.cloneWithRef=cloneWithRef,exports.createQuery=createQuery,exports.deprecationWarning=deprecationWarning,exports.getComputedStyle=getComputedStyle,exports.getDOMInfo=getDOMInfo,exports.getDOMMargin=getDOMMargin,exports.getDOMPadding=getDOMPadding,exports.styleInFlow=styleInFlow,exports.useCollector=useCollector,exports.useEffectOnce=useEffectOnce,exports.useMethods=useMethods,exports.wrapHookToRecognizeElement=wrapHookToRecognizeElement;
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var produce = require('immer');
var isEqualWith = require('lodash.isequalwith');
var React = require('react');
var invariant = require('tiny-invariant');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var produce__default = /*#__PURE__*/_interopDefaultLegacy(produce);
var isEqualWith__default = /*#__PURE__*/_interopDefaultLegacy(isEqualWith);
var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
var invariant__default = /*#__PURE__*/_interopDefaultLegacy(invariant);
var ROOT_NODE = 'ROOT';
var DEPRECATED_ROOT_NODE = 'canvas-ROOT';
// TODO: Use a better way to store/display error messages
var ERROR_NOPARENT = 'Parent id cannot be ommited';
var ERROR_DUPLICATE_NODEID = 'Attempting to add a node with duplicated id';
var ERROR_INVALID_NODEID = 'Node does not exist, it may have been removed';
var ERROR_TOP_LEVEL_ELEMENT_NO_ID = 'A <Element /> that is used inside a User Component must specify an `id` prop, eg: <Element id="text_element">...</Element> ';
var ERROR_MISSING_PLACEHOLDER_PLACEMENT = 'Placeholder required placement info (parent, index, or where) is missing';
var ERROR_MOVE_CANNOT_DROP = 'Node cannot be dropped into target parent';
var ERROR_MOVE_INCOMING_PARENT = 'Target parent rejects incoming node';
var ERROR_MOVE_OUTGOING_PARENT = 'Current parent rejects outgoing node';
var ERROR_MOVE_NONCANVAS_CHILD = 'Cannot move node that is not a direct child of a Canvas node';
var ERROR_MOVE_TO_NONCANVAS_PARENT = 'Cannot move node into a non-Canvas parent';
var ERROR_MOVE_TOP_LEVEL_NODE = 'A top-level Node cannot be moved';
var ERROR_MOVE_ROOT_NODE = 'Root Node cannot be moved';
var ERROR_MOVE_TO_DESCENDANT = 'Cannot move node into a descendant';
var ERROR_NOT_IN_RESOLVER = 'The component type specified for this node does not exist in the resolver';
var ERROR_INFINITE_CANVAS = "The component specified in the <Canvas> `is` prop has additional Canvas specified in it's render template.";
var ERROR_CANNOT_DRAG = 'The node has specified a canDrag() rule that prevents it from being dragged';
var ERROR_INVALID_NODE_ID = 'Invalid parameter Node Id specified';
var ERROR_DELETE_TOP_LEVEL_NODE = 'Attempting to delete a top-level Node';
var ERROR_RESOLVER_NOT_AN_OBJECT = "Resolver in <Editor /> has to be an object. For (de)serialization Craft.js needs a list of all the User Components. \n \nMore info: https://craft.js.org/r/docs/api/editor#props";
var ERROR_DESERIALIZE_COMPONENT_NOT_IN_RESOLVER = "An Error occurred while deserializing components: Cannot find component <%displayName% /> in resolver map. Please check your resolver in <Editor />\n\nAvailable components in resolver: %availableComponents%\n\nMore info: https://craft.js.org/r/docs/api/editor#props";
var _assign = function __assign() {
_assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
}
return t;
};
return _assign.apply(this, arguments);
};
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) {
s += arguments[i].length;
}
for (var r = Array(s), k = 0, i = 0; i < il; i++) {
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) {
r[k] = a[j];
}
}
return r;
}
var HISTORY_ACTIONS = {
UNDO: 'HISTORY_UNDO',
REDO: 'HISTORY_REDO',
THROTTLE: 'HISTORY_THROTTLE',
IGNORE: 'HISTORY_IGNORE',
};
var History = /** @class */ (function () {
function History() {
this.timeline = [];
this.pointer = -1;
}
History.prototype.add = function (patches, inversePatches) {
if (patches.length === 0 && inversePatches.length === 0) {
return;
}
this.pointer = this.pointer + 1;
this.timeline.length = this.pointer;
this.timeline[this.pointer] = {
patches: patches,
inversePatches: inversePatches,
timestamp: Date.now(),
};
};
History.prototype.throttleAdd = function (patches, inversePatches, throttleRate) {
if (throttleRate === void 0) { throttleRate = 500; }
if (patches.length === 0 && inversePatches.length === 0) {
return;
}
if (this.timeline.length && this.pointer >= 0) {
var _a = this.timeline[this.pointer], currPatches = _a.patches, timestamp = _a.timestamp;
var now = new Date();
var diff = now.getTime() - timestamp;
if (diff < throttleRate && currPatches.length === patches.length) {
var isSimilar = currPatches.every(function (currPatch, i) {
var currOp = currPatch.op, currPath = currPatch.path;
var _a = patches[i], op = _a.op, path = _a.path;
return op === currOp && isEqualWith__default['default'](path, currPath);
});
if (isSimilar) {
if (!this.throttledInversePatch) {
this.throttledInversePatch = inversePatches;
}
return;
}
}
}
this.add(patches, this.throttledInversePatch || inversePatches);
this.throttledInversePatch = null;
};
History.prototype.canUndo = function () {
return this.pointer >= 0;
};
History.prototype.canRedo = function () {
return this.pointer < this.timeline.length - 1;
};
History.prototype.undo = function (state) {
if (!this.canUndo()) {
return;
}
this.throttledInversePatch = null;
var inversePatches = this.timeline[this.pointer].inversePatches;
this.pointer = this.pointer - 1;
return produce.applyPatches(state, inversePatches);
};
History.prototype.redo = function (state) {
if (!this.canRedo()) {
return;
}
this.pointer = this.pointer + 1;
var patches = this.timeline[this.pointer].patches;
return produce.applyPatches(state, patches);
};
return History;
}());
function useMethods(methodsOrOptions, initialState, queryMethods, patchListener) {
var history = React.useMemo(function () { return new History(); }, []);
var methods;
var ignoreHistoryForActionsRef = React.useRef([]);
var normalizeHistoryRef = React.useRef();
if (typeof methodsOrOptions === 'function') {
methods = methodsOrOptions;
}
else {
methods = methodsOrOptions.methods;
ignoreHistoryForActionsRef.current = methodsOrOptions.ignoreHistoryForActions;
normalizeHistoryRef.current = methodsOrOptions.normalizeHistory;
}
var patchListenerRef = React.useRef(patchListener);
patchListenerRef.current = patchListener;
var _a = React.useMemo(function () {
var normalizeHistory = normalizeHistoryRef.current;
var ignoreHistoryForActions = ignoreHistoryForActionsRef.current;
var patchListener = patchListenerRef.current;
return [
function (state, action) {
var query = queryMethods && createQuery(queryMethods, function () { return state; }, history);
var finalState;
var _a = produce.produceWithPatches(state, function (draft) {
var _a, _b;
switch (action.type) {
case HISTORY_ACTIONS.UNDO: {
return history.undo(draft);
}
case HISTORY_ACTIONS.REDO: {
return history.redo(draft);
}
// TODO: Simplify History API
case HISTORY_ACTIONS.IGNORE:
case HISTORY_ACTIONS.THROTTLE: {
var _c = action.payload, type = _c[0], params = _c.slice(1);
(_a = methods(draft, query))[type].apply(_a, params);
break;
}
default:
(_b = methods(draft, query))[action.type].apply(_b, action.payload);
}
}), nextState = _a[0], patches = _a[1], inversePatches = _a[2];
finalState = nextState;
if (patchListener) {
patchListener(nextState, state, { type: action.type, params: action.payload, patches: patches }, query, function (cb) {
var normalizedDraft = produce.produceWithPatches(nextState, cb);
finalState = normalizedDraft[0];
patches = __spreadArrays(patches, normalizedDraft[1]);
inversePatches = __spreadArrays(normalizedDraft[2], inversePatches);
});
}
if ([HISTORY_ACTIONS.UNDO, HISTORY_ACTIONS.REDO].includes(action.type) &&
normalizeHistory) {
finalState = produce__default['default'](finalState, normalizeHistory);
}
if (!__spreadArrays(ignoreHistoryForActions, [
HISTORY_ACTIONS.UNDO,
HISTORY_ACTIONS.REDO,
HISTORY_ACTIONS.IGNORE,
]).includes(action.type)) {
if (action.type === HISTORY_ACTIONS.THROTTLE) {
history.throttleAdd(patches, inversePatches, action.config && action.config.rate);
}
else {
history.add(patches, inversePatches);
}
}
return finalState;
},
methods,
];
}, [history, methods, queryMethods]), reducer = _a[0], methodsFactory = _a[1];
var _b = React.useReducer(reducer, initialState), state = _b[0], dispatch = _b[1];
// Create ref for state, so we can use it inside memoized functions without having to add it as a dependency
var currState = React.useRef();
currState.current = state;
var query = React.useMemo(function () {
return !queryMethods
? []
: createQuery(queryMethods, function () { return currState.current; }, history);
}, [history, queryMethods]);
var actions = React.useMemo(function () {
var actionTypes = Object.keys(methodsFactory(null, null));
var ignoreHistoryForActions = ignoreHistoryForActionsRef.current;
return _assign(_assign({}, actionTypes.reduce(function (accum, type) {
accum[type] = function () {
var payload = [];
for (var _i = 0; _i < arguments.length; _i++) {
payload[_i] = arguments[_i];
}
return dispatch({ type: type, payload: payload });
};
return accum;
}, {})), { history: {
undo: function () {
return dispatch({
type: HISTORY_ACTIONS.UNDO,
});
},
redo: function () {
return dispatch({
type: HISTORY_ACTIONS.REDO,
});
},
throttle: function (rate) {
return _assign({}, actionTypes
.filter(function (type) { return !ignoreHistoryForActions.includes(type); })
.reduce(function (accum, type) {
accum[type] = function () {
var payload = [];
for (var _i = 0; _i < arguments.length; _i++) {
payload[_i] = arguments[_i];
}
return dispatch({
type: HISTORY_ACTIONS.THROTTLE,
payload: __spreadArrays([type], payload),
config: {
rate: rate,
},
});
};
return accum;
}, {}));
},
ignore: function () {
return _assign({}, actionTypes
.filter(function (type) { return !ignoreHistoryForActions.includes(type); })
.reduce(function (accum, type) {
accum[type] = function () {
var payload = [];
for (var _i = 0; _i < arguments.length; _i++) {
payload[_i] = arguments[_i];
}
return dispatch({
type: HISTORY_ACTIONS.IGNORE,
payload: __spreadArrays([type], payload),
});
};
return accum;
}, {}));
},
} });
}, [methodsFactory]);
var getState = React.useCallback(function () { return currState.current; }, []);
var watcher = React.useMemo(function () { return new Watcher(getState); }, [getState]);
React.useEffect(function () {
currState.current = state;
watcher.notify();
}, [state, watcher]);
return React.useMemo(function () { return ({
getState: getState,
subscribe: function (collector, cb, collectOnCreate) {
return watcher.subscribe(collector, cb, collectOnCreate);
},
actions: actions,
query: query,
history: history,
}); }, [actions, query, watcher, getState, history]);
}
function createQuery(queryMethods, getState, history) {
var queries = Object.keys(queryMethods()).reduce(function (accum, key) {
var _a;
return _assign(_assign({}, accum), (_a = {}, _a[key] = function () {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return (_a = queryMethods(getState()))[key].apply(_a, args);
}, _a));
}, {});
return _assign(_assign({}, queries), { history: {
canUndo: function () { return history.canUndo(); },
canRedo: function () { return history.canRedo(); },
} });
}
var Watcher = /** @class */ (function () {
function Watcher(getState) {
this.subscribers = [];
this.getState = getState;
}
/**
* Creates a Subscriber
* @returns {() => void} a Function that removes the Subscriber
*/
Watcher.prototype.subscribe = function (collector, onChange, collectOnCreate) {
var _this = this;
var subscriber = new Subscriber(function () { return collector(_this.getState()); }, onChange, collectOnCreate);
this.subscribers.push(subscriber);
return this.unsubscribe.bind(this, subscriber);
};
Watcher.prototype.unsubscribe = function (subscriber) {
if (this.subscribers.length) {
var index = this.subscribers.indexOf(subscriber);
if (index > -1)
return this.subscribers.splice(index, 1);
}
};
Watcher.prototype.notify = function () {
this.subscribers.forEach(function (subscriber) { return subscriber.collect(); });
};
return Watcher;
}());
var Subscriber = /** @class */ (function () {
/**
* Creates a Subscriber
* @param collector The method that returns an object of values to be collected
* @param onChange A callback method that is triggered when the collected values has changed
* @param collectOnCreate If set to true, the collector/onChange will be called on instantiation
*/
function Subscriber(collector, onChange, collectOnCreate) {
if (collectOnCreate === void 0) { collectOnCreate = false; }
this.collector = collector;
this.onChange = onChange;
// Collect and run onChange callback when Subscriber is created
if (collectOnCreate)
this.collect();
}
Subscriber.prototype.collect = function () {
try {
var recollect = this.collector();
if (!isEqualWith__default['default'](recollect, this.collected)) {
this.collected = recollect;
if (this.onChange)
this.onChange(this.collected);
}
}
catch (err) {
// eslint-disable-next-line no-console
console.warn(err);
}
};
return Subscriber;
}());
var getDOMPadding = function (dom) {
return {
left: parseInt(window.getComputedStyle(dom).paddingLeft),
right: parseInt(window.getComputedStyle(dom).paddingRight),
bottom: parseInt(window.getComputedStyle(dom).paddingTop),
top: parseInt(window.getComputedStyle(dom).paddingBottom),
};
};
var getDOMMargin = function (dom) {
return {
left: parseInt(window.getComputedStyle(dom).marginLeft),
right: parseInt(window.getComputedStyle(dom).marginRight),
bottom: parseInt(window.getComputedStyle(dom).marginTop),
top: parseInt(window.getComputedStyle(dom).marginBottom),
};
};
var getDOMInfo = function (dom) {
var _a = dom.getBoundingClientRect(), x = _a.x, y = _a.y, top = _a.top, left = _a.left, bottom = _a.bottom, right = _a.right, width = _a.width, height = _a.height;
var margin = getDOMMargin(dom), padding = getDOMPadding(dom);
return {
x: Math.round(x),
y: Math.round(y),
top: Math.round(top),
left: Math.round(left),
bottom: Math.round(bottom),
right: Math.round(right),
width: Math.round(width),
height: Math.round(height),
outerWidth: Math.round(width + margin.left + margin.right),
outerHeight: Math.round(height + margin.top + margin.bottom),
margin: margin,
padding: padding,
inFlow: dom && dom.parentElement && !!styleInFlow(dom, dom.parentElement),
};
};
var getComputedStyle = function (dom) {
return window.getComputedStyle(dom);
};
var styleInFlow = function (el, parent) {
var style = getComputedStyle(el);
var parentStyle = getComputedStyle(parent);
if (style.overflow && style.overflow !== 'visible')
return;
if (parentStyle.float !== 'none')
return;
if (parent &&
parentStyle.display === 'flex' &&
parentStyle['flex-direction'] !== 'column')
return;
switch (style.position) {
case 'static':
case 'relative':
break;
default:
return;
}
switch (el.tagName) {
case 'TR':
case 'TBODY':
case 'THEAD':
case 'TFOOT':
return true;
}
switch (style.display) {
case 'block':
case 'list-item':
case 'table':
case 'flex':
return true;
}
return;
};
function useCollector(store, collector) {
var subscribe = store.subscribe, getState = store.getState, actions = store.actions, query = store.query;
var initial = React.useRef(true);
var collected = React.useRef(null);
var collectorRef = React.useRef(collector);
collectorRef.current = collector;
var onCollect = React.useCallback(function (collected) {
return _assign(_assign({}, collected), { actions: actions, query: query });
}, [actions, query]);
// Collect states for initial render
if (initial.current && collector) {
collected.current = collector(getState(), query);
initial.current = false;
}
var _a = React.useState(onCollect(collected.current)), renderCollected = _a[0], setRenderCollected = _a[1];
// Collect states on state change
React.useEffect(function () {
var unsubscribe;
if (collectorRef.current) {
unsubscribe = subscribe(function (current) { return collectorRef.current(current, query); }, function (collected) {
setRenderCollected(onCollect(collected));
});
}
return function () {
if (unsubscribe)
unsubscribe();
};
}, [onCollect, query, subscribe]);
return renderCollected;
}
// https://github.com/react-dnd/react-dnd
function setRef(ref, node) {
if (node) {
if (typeof ref === 'function') {
ref(node);
}
else {
ref.current = node;
}
}
}
function cloneWithRef(element, newRef) {
var previousRef = element.ref;
invariant__default['default'](typeof previousRef !== 'string', 'Cannot connect to an element with an existing string ref. ' +
'Please convert it to use a callback ref instead, or wrap it into a <span> or <div>. ' +
'Read more: https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute');
if (!previousRef) {
// When there is no ref on the element, use the new ref directly
return React.cloneElement(element, {
ref: newRef,
});
}
else {
return React.cloneElement(element, {
ref: function (node) {
setRef(previousRef, node);
setRef(newRef, node);
},
});
}
}
function throwIfCompositeComponentElement(element) {
if (typeof element.type === 'string') {
return;
}
// const displayName =
// (element.type as any).displayName || element.type.name || 'the component'
// TODO: add error message
throw new Error();
}
function wrapHookToRecognizeElement(hook) {
return function (elementOrNode, opts) {
if (elementOrNode === void 0) { elementOrNode = null; }
// When passed a node, call the hook straight away.
if (!React.isValidElement(elementOrNode)) {
var node = elementOrNode;
node && hook(node, opts);
return node;
}
// If passed a ReactElement, clone it and attach this function as a ref.
// This helps us achieve a neat API where user doesn't even know that refs
// are being used under the hood.
var element = elementOrNode;
throwIfCompositeComponentElement(element);
return cloneWithRef(element, hook);
};
}
var RenderIndicator = function (_a) {
var style = _a.style;
return (React__default['default'].createElement("div", { style: _assign({ position: 'fixed', display: 'block', opacity: 1, borderStyle: 'solid', borderWidth: '1px', borderColor: 'transparent', zIndex: 99999 }, style) }));
};
var useEffectOnce = function (effect) {
React.useEffect(effect, []);
};
var deprecationWarning = function (name, payload) {
var message = "Deprecation warning: " + name + " will be deprecated in future relases.";
var suggest = payload.suggest, doc = payload.doc;
if (suggest) {
message += " Please use " + suggest + " instead.";
}
// URL link to Documentation
if (doc) {
message += "(" + doc + ")";
}
// eslint-disable-next-line no-console
console.warn(message);
};
exports.DEPRECATED_ROOT_NODE = DEPRECATED_ROOT_NODE;
exports.ERROR_CANNOT_DRAG = ERROR_CANNOT_DRAG;
exports.ERROR_DELETE_TOP_LEVEL_NODE = ERROR_DELETE_TOP_LEVEL_NODE;
exports.ERROR_DESERIALIZE_COMPONENT_NOT_IN_RESOLVER = ERROR_DESERIALIZE_COMPONENT_NOT_IN_RESOLVER;
exports.ERROR_DUPLICATE_NODEID = ERROR_DUPLICATE_NODEID;
exports.ERROR_INFINITE_CANVAS = ERROR_INFINITE_CANVAS;
exports.ERROR_INVALID_NODEID = ERROR_INVALID_NODEID;
exports.ERROR_INVALID_NODE_ID = ERROR_INVALID_NODE_ID;
exports.ERROR_MISSING_PLACEHOLDER_PLACEMENT = ERROR_MISSING_PLACEHOLDER_PLACEMENT;
exports.ERROR_MOVE_CANNOT_DROP = ERROR_MOVE_CANNOT_DROP;
exports.ERROR_MOVE_INCOMING_PARENT = ERROR_MOVE_INCOMING_PARENT;
exports.ERROR_MOVE_NONCANVAS_CHILD = ERROR_MOVE_NONCANVAS_CHILD;
exports.ERROR_MOVE_OUTGOING_PARENT = ERROR_MOVE_OUTGOING_PARENT;
exports.ERROR_MOVE_ROOT_NODE = ERROR_MOVE_ROOT_NODE;
exports.ERROR_MOVE_TOP_LEVEL_NODE = ERROR_MOVE_TOP_LEVEL_NODE;
exports.ERROR_MOVE_TO_DESCENDANT = ERROR_MOVE_TO_DESCENDANT;
exports.ERROR_MOVE_TO_NONCANVAS_PARENT = ERROR_MOVE_TO_NONCANVAS_PARENT;
exports.ERROR_NOPARENT = ERROR_NOPARENT;
exports.ERROR_NOT_IN_RESOLVER = ERROR_NOT_IN_RESOLVER;
exports.ERROR_RESOLVER_NOT_AN_OBJECT = ERROR_RESOLVER_NOT_AN_OBJECT;
exports.ERROR_TOP_LEVEL_ELEMENT_NO_ID = ERROR_TOP_LEVEL_ELEMENT_NO_ID;
exports.HISTORY_ACTIONS = HISTORY_ACTIONS;
exports.History = History;
exports.ROOT_NODE = ROOT_NODE;
exports.RenderIndicator = RenderIndicator;
exports.cloneWithRef = cloneWithRef;
exports.createQuery = createQuery;
exports.deprecationWarning = deprecationWarning;
exports.getComputedStyle = getComputedStyle;
exports.getDOMInfo = getDOMInfo;
exports.getDOMMargin = getDOMMargin;
exports.getDOMPadding = getDOMPadding;
exports.styleInFlow = styleInFlow;
exports.useCollector = useCollector;
exports.useEffectOnce = useEffectOnce;
exports.useMethods = useMethods;
exports.wrapHookToRecognizeElement = wrapHookToRecognizeElement;

@@ -1,1 +0,555 @@

import t,{applyPatches as e,produceWithPatches as n}from"immer";import r from"lodash.isequalwith";import o,{useMemo as i,useRef as a,useReducer as c,useCallback as s,useEffect as u,useState as d,cloneElement as p,isValidElement as l}from"react";import h from"tiny-invariant";var f="ROOT",m="canvas-ROOT",g="Parent id cannot be ommited",v="Attempting to add a node with duplicated id",y="Node does not exist, it may have been removed",b='A <Element /> that is used inside a User Component must specify an `id` prop, eg: <Element id="text_element">...</Element> ',w="Placeholder required placement info (parent, index, or where) is missing",O="Node cannot be dropped into target parent",R="Target parent rejects incoming node",T="Current parent rejects outgoing node",C="Cannot move node that is not a direct child of a Canvas node",E="Cannot move node into a non-Canvas parent",I="A top-level Node cannot be moved",N="Root Node cannot be moved",D="Cannot move node into a descendant",S="The component type specified for this node does not exist in the resolver",x="The component specified in the <Canvas> `is` prop has additional Canvas specified in it's render template.",H="The node has specified a canDrag() rule that prevents it from being dragged",P="Invalid parameter Node Id specified",M="Attempting to delete a top-level Node",U="Resolver in <Editor /> has to be an object. For (de)serialization Craft.js needs a list of all the User Components. \n \nMore info: https://craft.js.org/r/docs/api/editor#props",A="An Error occurred while deserializing components: Cannot find component <%displayName% /> in resolver map. Please check your resolver in <Editor />\n\nAvailable components in resolver: %availableComponents%\n\nMore info: https://craft.js.org/r/docs/api/editor#props",j=function(){return(j=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t}).apply(this,arguments)};function k(){for(var t=0,e=0,n=arguments.length;e<n;e++)t+=arguments[e].length;var r=Array(t),o=0;for(e=0;e<n;e++)for(var i=arguments[e],a=0,c=i.length;a<c;a++,o++)r[o]=i[a];return r}var L={UNDO:"HISTORY_UNDO",REDO:"HISTORY_REDO",THROTTLE:"HISTORY_THROTTLE",IGNORE:"HISTORY_IGNORE"},q=function(){function t(){this.timeline=[],this.pointer=-1}return t.prototype.add=function(t,e){0===t.length&&0===e.length||(this.pointer=this.pointer+1,this.timeline.length=this.pointer,this.timeline[this.pointer]={patches:t,inversePatches:e,timestamp:Date.now()})},t.prototype.throttleAdd=function(t,e,n){if(void 0===n&&(n=500),0!==t.length||0!==e.length){if(this.timeline.length&&this.pointer>=0){var o=this.timeline[this.pointer],i=o.patches,a=o.timestamp;if((new Date).getTime()-a<n&&i.length===t.length&&i.every((function(e,n){var o=t[n];return o.op===e.op&&r(o.path,e.path)})))return void(this.throttledInversePatch||(this.throttledInversePatch=e))}this.add(t,this.throttledInversePatch||e),this.throttledInversePatch=null}},t.prototype.canUndo=function(){return this.pointer>=0},t.prototype.canRedo=function(){return this.pointer<this.timeline.length-1},t.prototype.undo=function(t){if(this.canUndo()){this.throttledInversePatch=null;var n=this.timeline[this.pointer].inversePatches;return this.pointer=this.pointer-1,e(t,n)}},t.prototype.redo=function(t){if(this.canRedo())return this.pointer=this.pointer+1,e(t,this.timeline[this.pointer].patches)},t}();function G(e,r,o,d){var p,l=i((function(){return new q}),[]),h=a([]),f=a();"function"==typeof e?p=e:(p=e.methods,h.current=e.ignoreHistoryForActions,f.current=e.normalizeHistory);var m=a(d);m.current=d;var g=i((function(){var e=f.current,r=h.current,i=m.current;return[function(a,c){var s,u=o&&Y(o,(function(){return a}),l),d=n(a,(function(t){var e,n;switch(c.type){case L.UNDO:return l.undo(t);case L.REDO:return l.redo(t);case L.IGNORE:case L.THROTTLE:var r=c.payload,o=r[0],i=r.slice(1);(e=p(t,u))[o].apply(e,i);break;default:(n=p(t,u))[c.type].apply(n,c.payload)}})),h=d[0],f=d[1],m=d[2];return s=h,i&&i(h,a,{type:c.type,params:c.payload,patches:f},u,(function(t){var e=n(h,t);s=e[0],f=k(f,e[1]),m=k(e[2],m)})),[L.UNDO,L.REDO].includes(c.type)&&e&&(s=t(s,e)),k(r,[L.UNDO,L.REDO,L.IGNORE]).includes(c.type)||(c.type===L.THROTTLE?l.throttleAdd(f,m,c.config&&c.config.rate):l.add(f,m)),s},p]}),[l,p,o]),v=g[1],y=c(g[0],r),b=y[0],w=y[1],O=a();O.current=b;var R=i((function(){return o?Y(o,(function(){return O.current}),l):[]}),[l,o]),T=i((function(){var t=Object.keys(v(null,null)),e=h.current;return j(j({},t.reduce((function(t,e){return t[e]=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return w({type:e,payload:t})},t}),{})),{history:{undo:function(){return w({type:L.UNDO})},redo:function(){return w({type:L.REDO})},throttle:function(n){return j({},t.filter((function(t){return!e.includes(t)})).reduce((function(t,e){return t[e]=function(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];return w({type:L.THROTTLE,payload:k([e],t),config:{rate:n}})},t}),{}))},ignore:function(){return j({},t.filter((function(t){return!e.includes(t)})).reduce((function(t,e){return t[e]=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return w({type:L.IGNORE,payload:k([e],t)})},t}),{}))}}})}),[v]),C=s((function(){return O.current}),[]),E=i((function(){return new _(C)}),[C]);return u((function(){O.current=b,E.notify()}),[b,E]),i((function(){return{getState:C,subscribe:function(t,e,n){return E.subscribe(t,e,n)},actions:T,query:R,history:l}}),[T,R,E,C,l])}function Y(t,e,n){var r=Object.keys(t()).reduce((function(n,r){var o;return j(j({},n),((o={})[r]=function(){for(var n,o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];return(n=t(e()))[r].apply(n,o)},o))}),{});return j(j({},r),{history:{canUndo:function(){return n.canUndo()},canRedo:function(){return n.canRedo()}}})}var _=function(){function t(t){this.subscribers=[],this.getState=t}return t.prototype.subscribe=function(t,e,n){var r=this,o=new z((function(){return t(r.getState())}),e,n);return this.subscribers.push(o),this.unsubscribe.bind(this,o)},t.prototype.unsubscribe=function(t){if(this.subscribers.length){var e=this.subscribers.indexOf(t);if(e>-1)return this.subscribers.splice(e,1)}},t.prototype.notify=function(){this.subscribers.forEach((function(t){return t.collect()}))},t}(),z=function(){function t(t,e,n){void 0===n&&(n=!1),this.collector=t,this.onChange=e,n&&this.collect()}return t.prototype.collect=function(){try{var t=this.collector();r(t,this.collected)||(this.collected=t,this.onChange&&this.onChange(this.collected))}catch(t){console.warn(t)}},t}(),B=function(t){return{left:parseInt(window.getComputedStyle(t).paddingLeft),right:parseInt(window.getComputedStyle(t).paddingRight),bottom:parseInt(window.getComputedStyle(t).paddingTop),top:parseInt(window.getComputedStyle(t).paddingBottom)}},F=function(t){return{left:parseInt(window.getComputedStyle(t).marginLeft),right:parseInt(window.getComputedStyle(t).marginRight),bottom:parseInt(window.getComputedStyle(t).marginTop),top:parseInt(window.getComputedStyle(t).marginBottom)}},W=function(t){var e=t.getBoundingClientRect(),n=e.x,r=e.y,o=e.top,i=e.left,a=e.bottom,c=e.right,s=e.width,u=e.height,d=F(t),p=B(t);return{x:Math.round(n),y:Math.round(r),top:Math.round(o),left:Math.round(i),bottom:Math.round(a),right:Math.round(c),width:Math.round(s),height:Math.round(u),outerWidth:Math.round(s+d.left+d.right),outerHeight:Math.round(u+d.top+d.bottom),margin:d,padding:p,inFlow:t&&t.parentElement&&!!K(t,t.parentElement)}},J=function(t){return window.getComputedStyle(t)},K=function(t,e){var n=J(t),r=J(e);if(!(n.overflow&&"visible"!==n.overflow||"none"!==r.float||e&&"flex"===r.display&&"column"!==r["flex-direction"])){switch(n.position){case"static":case"relative":break;default:return}switch(t.tagName){case"TR":case"TBODY":case"THEAD":case"TFOOT":return!0}switch(n.display){case"block":case"list-item":case"table":case"flex":return!0}}};function Q(t,e){var n=t.subscribe,r=t.getState,o=t.actions,i=t.query,c=a(!0),p=a(null),l=a(e);l.current=e;var h=s((function(t){return j(j({},t),{actions:o,query:i})}),[o,i]);c.current&&e&&(p.current=e(r(),i),c.current=!1);var f=d(h(p.current)),m=f[0],g=f[1];return u((function(){var t;return l.current&&(t=n((function(t){return l.current(t,i)}),(function(t){g(h(t))}))),function(){t&&t()}}),[h,i,n]),m}function V(t,e){e&&("function"==typeof t?t(e):t.current=e)}function X(t,e){var n=t.ref;return h("string"!=typeof n,"Cannot connect to an element with an existing string ref. Please convert it to use a callback ref instead, or wrap it into a <span> or <div>. Read more: https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute"),p(t,n?{ref:function(t){V(n,t),V(e,t)}}:{ref:e})}function Z(t){return function(e,n){if(void 0===e&&(e=null),!l(e)){var r=e;return r&&t(r,n),r}var o=e;return function(t){if("string"!=typeof t.type)throw new Error}(o),X(o,t)}}var $=function(t){return o.createElement("div",{style:j({position:"fixed",display:"block",opacity:1,borderStyle:"solid",borderWidth:"1px",borderColor:"transparent",zIndex:99999},t.style)})},tt=function(t){u(t,[])},et=function(t,e){var n="Deprecation warning: "+t+" will be deprecated in future relases.",r=e.suggest,o=e.doc;r&&(n+=" Please use "+r+" instead."),o&&(n+="("+o+")"),console.warn(n)};export{m as DEPRECATED_ROOT_NODE,H as ERROR_CANNOT_DRAG,M as ERROR_DELETE_TOP_LEVEL_NODE,A as ERROR_DESERIALIZE_COMPONENT_NOT_IN_RESOLVER,v as ERROR_DUPLICATE_NODEID,x as ERROR_INFINITE_CANVAS,y as ERROR_INVALID_NODEID,P as ERROR_INVALID_NODE_ID,w as ERROR_MISSING_PLACEHOLDER_PLACEMENT,O as ERROR_MOVE_CANNOT_DROP,R as ERROR_MOVE_INCOMING_PARENT,C as ERROR_MOVE_NONCANVAS_CHILD,T as ERROR_MOVE_OUTGOING_PARENT,N as ERROR_MOVE_ROOT_NODE,I as ERROR_MOVE_TOP_LEVEL_NODE,D as ERROR_MOVE_TO_DESCENDANT,E as ERROR_MOVE_TO_NONCANVAS_PARENT,g as ERROR_NOPARENT,S as ERROR_NOT_IN_RESOLVER,U as ERROR_RESOLVER_NOT_AN_OBJECT,b as ERROR_TOP_LEVEL_ELEMENT_NO_ID,L as HISTORY_ACTIONS,q as History,f as ROOT_NODE,$ as RenderIndicator,X as cloneWithRef,Y as createQuery,et as deprecationWarning,J as getComputedStyle,W as getDOMInfo,F as getDOMMargin,B as getDOMPadding,K as styleInFlow,Q as useCollector,tt as useEffectOnce,G as useMethods,Z as wrapHookToRecognizeElement};
import produce, { applyPatches, produceWithPatches } from 'immer';
import isEqualWith from 'lodash.isequalwith';
import React, { useMemo, useRef, useReducer, useCallback, useEffect, useState, cloneElement, isValidElement } from 'react';
import invariant from 'tiny-invariant';
var ROOT_NODE = 'ROOT';
var DEPRECATED_ROOT_NODE = 'canvas-ROOT';
// TODO: Use a better way to store/display error messages
var ERROR_NOPARENT = 'Parent id cannot be ommited';
var ERROR_DUPLICATE_NODEID = 'Attempting to add a node with duplicated id';
var ERROR_INVALID_NODEID = 'Node does not exist, it may have been removed';
var ERROR_TOP_LEVEL_ELEMENT_NO_ID = 'A <Element /> that is used inside a User Component must specify an `id` prop, eg: <Element id="text_element">...</Element> ';
var ERROR_MISSING_PLACEHOLDER_PLACEMENT = 'Placeholder required placement info (parent, index, or where) is missing';
var ERROR_MOVE_CANNOT_DROP = 'Node cannot be dropped into target parent';
var ERROR_MOVE_INCOMING_PARENT = 'Target parent rejects incoming node';
var ERROR_MOVE_OUTGOING_PARENT = 'Current parent rejects outgoing node';
var ERROR_MOVE_NONCANVAS_CHILD = 'Cannot move node that is not a direct child of a Canvas node';
var ERROR_MOVE_TO_NONCANVAS_PARENT = 'Cannot move node into a non-Canvas parent';
var ERROR_MOVE_TOP_LEVEL_NODE = 'A top-level Node cannot be moved';
var ERROR_MOVE_ROOT_NODE = 'Root Node cannot be moved';
var ERROR_MOVE_TO_DESCENDANT = 'Cannot move node into a descendant';
var ERROR_NOT_IN_RESOLVER = 'The component type specified for this node does not exist in the resolver';
var ERROR_INFINITE_CANVAS = "The component specified in the <Canvas> `is` prop has additional Canvas specified in it's render template.";
var ERROR_CANNOT_DRAG = 'The node has specified a canDrag() rule that prevents it from being dragged';
var ERROR_INVALID_NODE_ID = 'Invalid parameter Node Id specified';
var ERROR_DELETE_TOP_LEVEL_NODE = 'Attempting to delete a top-level Node';
var ERROR_RESOLVER_NOT_AN_OBJECT = "Resolver in <Editor /> has to be an object. For (de)serialization Craft.js needs a list of all the User Components. \n \nMore info: https://craft.js.org/r/docs/api/editor#props";
var ERROR_DESERIALIZE_COMPONENT_NOT_IN_RESOLVER = "An Error occurred while deserializing components: Cannot find component <%displayName% /> in resolver map. Please check your resolver in <Editor />\n\nAvailable components in resolver: %availableComponents%\n\nMore info: https://craft.js.org/r/docs/api/editor#props";
var _assign = function __assign() {
_assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
}
return t;
};
return _assign.apply(this, arguments);
};
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) {
s += arguments[i].length;
}
for (var r = Array(s), k = 0, i = 0; i < il; i++) {
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) {
r[k] = a[j];
}
}
return r;
}
var HISTORY_ACTIONS = {
UNDO: 'HISTORY_UNDO',
REDO: 'HISTORY_REDO',
THROTTLE: 'HISTORY_THROTTLE',
IGNORE: 'HISTORY_IGNORE',
};
var History = /** @class */ (function () {
function History() {
this.timeline = [];
this.pointer = -1;
}
History.prototype.add = function (patches, inversePatches) {
if (patches.length === 0 && inversePatches.length === 0) {
return;
}
this.pointer = this.pointer + 1;
this.timeline.length = this.pointer;
this.timeline[this.pointer] = {
patches: patches,
inversePatches: inversePatches,
timestamp: Date.now(),
};
};
History.prototype.throttleAdd = function (patches, inversePatches, throttleRate) {
if (throttleRate === void 0) { throttleRate = 500; }
if (patches.length === 0 && inversePatches.length === 0) {
return;
}
if (this.timeline.length && this.pointer >= 0) {
var _a = this.timeline[this.pointer], currPatches = _a.patches, timestamp = _a.timestamp;
var now = new Date();
var diff = now.getTime() - timestamp;
if (diff < throttleRate && currPatches.length === patches.length) {
var isSimilar = currPatches.every(function (currPatch, i) {
var currOp = currPatch.op, currPath = currPatch.path;
var _a = patches[i], op = _a.op, path = _a.path;
return op === currOp && isEqualWith(path, currPath);
});
if (isSimilar) {
if (!this.throttledInversePatch) {
this.throttledInversePatch = inversePatches;
}
return;
}
}
}
this.add(patches, this.throttledInversePatch || inversePatches);
this.throttledInversePatch = null;
};
History.prototype.canUndo = function () {
return this.pointer >= 0;
};
History.prototype.canRedo = function () {
return this.pointer < this.timeline.length - 1;
};
History.prototype.undo = function (state) {
if (!this.canUndo()) {
return;
}
this.throttledInversePatch = null;
var inversePatches = this.timeline[this.pointer].inversePatches;
this.pointer = this.pointer - 1;
return applyPatches(state, inversePatches);
};
History.prototype.redo = function (state) {
if (!this.canRedo()) {
return;
}
this.pointer = this.pointer + 1;
var patches = this.timeline[this.pointer].patches;
return applyPatches(state, patches);
};
return History;
}());
function useMethods(methodsOrOptions, initialState, queryMethods, patchListener) {
var history = useMemo(function () { return new History(); }, []);
var methods;
var ignoreHistoryForActionsRef = useRef([]);
var normalizeHistoryRef = useRef();
if (typeof methodsOrOptions === 'function') {
methods = methodsOrOptions;
}
else {
methods = methodsOrOptions.methods;
ignoreHistoryForActionsRef.current = methodsOrOptions.ignoreHistoryForActions;
normalizeHistoryRef.current = methodsOrOptions.normalizeHistory;
}
var patchListenerRef = useRef(patchListener);
patchListenerRef.current = patchListener;
var _a = useMemo(function () {
var normalizeHistory = normalizeHistoryRef.current;
var ignoreHistoryForActions = ignoreHistoryForActionsRef.current;
var patchListener = patchListenerRef.current;
return [
function (state, action) {
var query = queryMethods && createQuery(queryMethods, function () { return state; }, history);
var finalState;
var _a = produceWithPatches(state, function (draft) {
var _a, _b;
switch (action.type) {
case HISTORY_ACTIONS.UNDO: {
return history.undo(draft);
}
case HISTORY_ACTIONS.REDO: {
return history.redo(draft);
}
// TODO: Simplify History API
case HISTORY_ACTIONS.IGNORE:
case HISTORY_ACTIONS.THROTTLE: {
var _c = action.payload, type = _c[0], params = _c.slice(1);
(_a = methods(draft, query))[type].apply(_a, params);
break;
}
default:
(_b = methods(draft, query))[action.type].apply(_b, action.payload);
}
}), nextState = _a[0], patches = _a[1], inversePatches = _a[2];
finalState = nextState;
if (patchListener) {
patchListener(nextState, state, { type: action.type, params: action.payload, patches: patches }, query, function (cb) {
var normalizedDraft = produceWithPatches(nextState, cb);
finalState = normalizedDraft[0];
patches = __spreadArrays(patches, normalizedDraft[1]);
inversePatches = __spreadArrays(normalizedDraft[2], inversePatches);
});
}
if ([HISTORY_ACTIONS.UNDO, HISTORY_ACTIONS.REDO].includes(action.type) &&
normalizeHistory) {
finalState = produce(finalState, normalizeHistory);
}
if (!__spreadArrays(ignoreHistoryForActions, [
HISTORY_ACTIONS.UNDO,
HISTORY_ACTIONS.REDO,
HISTORY_ACTIONS.IGNORE,
]).includes(action.type)) {
if (action.type === HISTORY_ACTIONS.THROTTLE) {
history.throttleAdd(patches, inversePatches, action.config && action.config.rate);
}
else {
history.add(patches, inversePatches);
}
}
return finalState;
},
methods,
];
}, [history, methods, queryMethods]), reducer = _a[0], methodsFactory = _a[1];
var _b = useReducer(reducer, initialState), state = _b[0], dispatch = _b[1];
// Create ref for state, so we can use it inside memoized functions without having to add it as a dependency
var currState = useRef();
currState.current = state;
var query = useMemo(function () {
return !queryMethods
? []
: createQuery(queryMethods, function () { return currState.current; }, history);
}, [history, queryMethods]);
var actions = useMemo(function () {
var actionTypes = Object.keys(methodsFactory(null, null));
var ignoreHistoryForActions = ignoreHistoryForActionsRef.current;
return _assign(_assign({}, actionTypes.reduce(function (accum, type) {
accum[type] = function () {
var payload = [];
for (var _i = 0; _i < arguments.length; _i++) {
payload[_i] = arguments[_i];
}
return dispatch({ type: type, payload: payload });
};
return accum;
}, {})), { history: {
undo: function () {
return dispatch({
type: HISTORY_ACTIONS.UNDO,
});
},
redo: function () {
return dispatch({
type: HISTORY_ACTIONS.REDO,
});
},
throttle: function (rate) {
return _assign({}, actionTypes
.filter(function (type) { return !ignoreHistoryForActions.includes(type); })
.reduce(function (accum, type) {
accum[type] = function () {
var payload = [];
for (var _i = 0; _i < arguments.length; _i++) {
payload[_i] = arguments[_i];
}
return dispatch({
type: HISTORY_ACTIONS.THROTTLE,
payload: __spreadArrays([type], payload),
config: {
rate: rate,
},
});
};
return accum;
}, {}));
},
ignore: function () {
return _assign({}, actionTypes
.filter(function (type) { return !ignoreHistoryForActions.includes(type); })
.reduce(function (accum, type) {
accum[type] = function () {
var payload = [];
for (var _i = 0; _i < arguments.length; _i++) {
payload[_i] = arguments[_i];
}
return dispatch({
type: HISTORY_ACTIONS.IGNORE,
payload: __spreadArrays([type], payload),
});
};
return accum;
}, {}));
},
} });
}, [methodsFactory]);
var getState = useCallback(function () { return currState.current; }, []);
var watcher = useMemo(function () { return new Watcher(getState); }, [getState]);
useEffect(function () {
currState.current = state;
watcher.notify();
}, [state, watcher]);
return useMemo(function () { return ({
getState: getState,
subscribe: function (collector, cb, collectOnCreate) {
return watcher.subscribe(collector, cb, collectOnCreate);
},
actions: actions,
query: query,
history: history,
}); }, [actions, query, watcher, getState, history]);
}
function createQuery(queryMethods, getState, history) {
var queries = Object.keys(queryMethods()).reduce(function (accum, key) {
var _a;
return _assign(_assign({}, accum), (_a = {}, _a[key] = function () {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return (_a = queryMethods(getState()))[key].apply(_a, args);
}, _a));
}, {});
return _assign(_assign({}, queries), { history: {
canUndo: function () { return history.canUndo(); },
canRedo: function () { return history.canRedo(); },
} });
}
var Watcher = /** @class */ (function () {
function Watcher(getState) {
this.subscribers = [];
this.getState = getState;
}
/**
* Creates a Subscriber
* @returns {() => void} a Function that removes the Subscriber
*/
Watcher.prototype.subscribe = function (collector, onChange, collectOnCreate) {
var _this = this;
var subscriber = new Subscriber(function () { return collector(_this.getState()); }, onChange, collectOnCreate);
this.subscribers.push(subscriber);
return this.unsubscribe.bind(this, subscriber);
};
Watcher.prototype.unsubscribe = function (subscriber) {
if (this.subscribers.length) {
var index = this.subscribers.indexOf(subscriber);
if (index > -1)
return this.subscribers.splice(index, 1);
}
};
Watcher.prototype.notify = function () {
this.subscribers.forEach(function (subscriber) { return subscriber.collect(); });
};
return Watcher;
}());
var Subscriber = /** @class */ (function () {
/**
* Creates a Subscriber
* @param collector The method that returns an object of values to be collected
* @param onChange A callback method that is triggered when the collected values has changed
* @param collectOnCreate If set to true, the collector/onChange will be called on instantiation
*/
function Subscriber(collector, onChange, collectOnCreate) {
if (collectOnCreate === void 0) { collectOnCreate = false; }
this.collector = collector;
this.onChange = onChange;
// Collect and run onChange callback when Subscriber is created
if (collectOnCreate)
this.collect();
}
Subscriber.prototype.collect = function () {
try {
var recollect = this.collector();
if (!isEqualWith(recollect, this.collected)) {
this.collected = recollect;
if (this.onChange)
this.onChange(this.collected);
}
}
catch (err) {
// eslint-disable-next-line no-console
console.warn(err);
}
};
return Subscriber;
}());
var getDOMPadding = function (dom) {
return {
left: parseInt(window.getComputedStyle(dom).paddingLeft),
right: parseInt(window.getComputedStyle(dom).paddingRight),
bottom: parseInt(window.getComputedStyle(dom).paddingTop),
top: parseInt(window.getComputedStyle(dom).paddingBottom),
};
};
var getDOMMargin = function (dom) {
return {
left: parseInt(window.getComputedStyle(dom).marginLeft),
right: parseInt(window.getComputedStyle(dom).marginRight),
bottom: parseInt(window.getComputedStyle(dom).marginTop),
top: parseInt(window.getComputedStyle(dom).marginBottom),
};
};
var getDOMInfo = function (dom) {
var _a = dom.getBoundingClientRect(), x = _a.x, y = _a.y, top = _a.top, left = _a.left, bottom = _a.bottom, right = _a.right, width = _a.width, height = _a.height;
var margin = getDOMMargin(dom), padding = getDOMPadding(dom);
return {
x: Math.round(x),
y: Math.round(y),
top: Math.round(top),
left: Math.round(left),
bottom: Math.round(bottom),
right: Math.round(right),
width: Math.round(width),
height: Math.round(height),
outerWidth: Math.round(width + margin.left + margin.right),
outerHeight: Math.round(height + margin.top + margin.bottom),
margin: margin,
padding: padding,
inFlow: dom && dom.parentElement && !!styleInFlow(dom, dom.parentElement),
};
};
var getComputedStyle = function (dom) {
return window.getComputedStyle(dom);
};
var styleInFlow = function (el, parent) {
var style = getComputedStyle(el);
var parentStyle = getComputedStyle(parent);
if (style.overflow && style.overflow !== 'visible')
return;
if (parentStyle.float !== 'none')
return;
if (parent &&
parentStyle.display === 'flex' &&
parentStyle['flex-direction'] !== 'column')
return;
switch (style.position) {
case 'static':
case 'relative':
break;
default:
return;
}
switch (el.tagName) {
case 'TR':
case 'TBODY':
case 'THEAD':
case 'TFOOT':
return true;
}
switch (style.display) {
case 'block':
case 'list-item':
case 'table':
case 'flex':
return true;
}
return;
};
function useCollector(store, collector) {
var subscribe = store.subscribe, getState = store.getState, actions = store.actions, query = store.query;
var initial = useRef(true);
var collected = useRef(null);
var collectorRef = useRef(collector);
collectorRef.current = collector;
var onCollect = useCallback(function (collected) {
return _assign(_assign({}, collected), { actions: actions, query: query });
}, [actions, query]);
// Collect states for initial render
if (initial.current && collector) {
collected.current = collector(getState(), query);
initial.current = false;
}
var _a = useState(onCollect(collected.current)), renderCollected = _a[0], setRenderCollected = _a[1];
// Collect states on state change
useEffect(function () {
var unsubscribe;
if (collectorRef.current) {
unsubscribe = subscribe(function (current) { return collectorRef.current(current, query); }, function (collected) {
setRenderCollected(onCollect(collected));
});
}
return function () {
if (unsubscribe)
unsubscribe();
};
}, [onCollect, query, subscribe]);
return renderCollected;
}
// https://github.com/react-dnd/react-dnd
function setRef(ref, node) {
if (node) {
if (typeof ref === 'function') {
ref(node);
}
else {
ref.current = node;
}
}
}
function cloneWithRef(element, newRef) {
var previousRef = element.ref;
invariant(typeof previousRef !== 'string', 'Cannot connect to an element with an existing string ref. ' +
'Please convert it to use a callback ref instead, or wrap it into a <span> or <div>. ' +
'Read more: https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute');
if (!previousRef) {
// When there is no ref on the element, use the new ref directly
return cloneElement(element, {
ref: newRef,
});
}
else {
return cloneElement(element, {
ref: function (node) {
setRef(previousRef, node);
setRef(newRef, node);
},
});
}
}
function throwIfCompositeComponentElement(element) {
if (typeof element.type === 'string') {
return;
}
// const displayName =
// (element.type as any).displayName || element.type.name || 'the component'
// TODO: add error message
throw new Error();
}
function wrapHookToRecognizeElement(hook) {
return function (elementOrNode, opts) {
if (elementOrNode === void 0) { elementOrNode = null; }
// When passed a node, call the hook straight away.
if (!isValidElement(elementOrNode)) {
var node = elementOrNode;
node && hook(node, opts);
return node;
}
// If passed a ReactElement, clone it and attach this function as a ref.
// This helps us achieve a neat API where user doesn't even know that refs
// are being used under the hood.
var element = elementOrNode;
throwIfCompositeComponentElement(element);
return cloneWithRef(element, hook);
};
}
var RenderIndicator = function (_a) {
var style = _a.style;
return (React.createElement("div", { style: _assign({ position: 'fixed', display: 'block', opacity: 1, borderStyle: 'solid', borderWidth: '1px', borderColor: 'transparent', zIndex: 99999 }, style) }));
};
var useEffectOnce = function (effect) {
useEffect(effect, []);
};
var deprecationWarning = function (name, payload) {
var message = "Deprecation warning: " + name + " will be deprecated in future relases.";
var suggest = payload.suggest, doc = payload.doc;
if (suggest) {
message += " Please use " + suggest + " instead.";
}
// URL link to Documentation
if (doc) {
message += "(" + doc + ")";
}
// eslint-disable-next-line no-console
console.warn(message);
};
export { DEPRECATED_ROOT_NODE, ERROR_CANNOT_DRAG, ERROR_DELETE_TOP_LEVEL_NODE, ERROR_DESERIALIZE_COMPONENT_NOT_IN_RESOLVER, ERROR_DUPLICATE_NODEID, ERROR_INFINITE_CANVAS, ERROR_INVALID_NODEID, ERROR_INVALID_NODE_ID, ERROR_MISSING_PLACEHOLDER_PLACEMENT, ERROR_MOVE_CANNOT_DROP, ERROR_MOVE_INCOMING_PARENT, ERROR_MOVE_NONCANVAS_CHILD, ERROR_MOVE_OUTGOING_PARENT, ERROR_MOVE_ROOT_NODE, ERROR_MOVE_TOP_LEVEL_NODE, ERROR_MOVE_TO_DESCENDANT, ERROR_MOVE_TO_NONCANVAS_PARENT, ERROR_NOPARENT, ERROR_NOT_IN_RESOLVER, ERROR_RESOLVER_NOT_AN_OBJECT, ERROR_TOP_LEVEL_ELEMENT_NO_ID, HISTORY_ACTIONS, History, ROOT_NODE, RenderIndicator, cloneWithRef, createQuery, deprecationWarning, getComputedStyle, getDOMInfo, getDOMMargin, getDOMPadding, styleInFlow, useCollector, useEffectOnce, useMethods, wrapHookToRecognizeElement };

4

package.json

@@ -5,3 +5,3 @@ {

"private": false,
"version": "0.1.0-beta.13",
"version": "0.2.0-alpha.0",
"author": "Prev Wong <prevwong@gmail.com>",

@@ -27,3 +27,3 @@ "license": "MIT",

},
"gitHead": "466358b2604fbe5c40bc2d8dad35d51252de2d48"
"gitHead": "0a14fe4f3661edd684effcff11bc141a3ed94cbe"
}

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc