@embeddable.com/sdk-react 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+
2
+ > @embeddable-sdk/react@0.0.1 build
3
+ > rollup -c
4
+
5
+ (node:41139) ExperimentalWarning: Import assertions are not a stable feature of the JavaScript language. Avoid relying on their current behavior and syntax as those might change in a future version of Node.js.
6
+ (Use `node --trace-warnings ...` to show where the warning was created)
7
+ (node:41139) ExperimentalWarning: Importing JSON modules is an experimental feature and might change at any time
8
+ 
9
+ ./src/index.ts → lib/index.umd.js...
10
+ (!) Plugin typescript: @rollup/plugin-typescript: Rollup 'sourcemap' option must be set to generate source maps.
11
+ created lib/index.umd.js in 732ms
12
+ 
13
+ ./src/index.ts → lib/index.cjs.js, lib/index.esm.js...
14
+ (!) Plugin typescript: @rollup/plugin-typescript: Rollup 'sourcemap' option must be set to generate source maps.
15
+ created lib/index.cjs.js, lib/index.esm.js in 366ms
package/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # @embeddable.com/sdk-react
2
+
3
+ ## 0.0.1
4
+
5
+ ### Patch Changes
6
+
7
+ - First publish attempt.
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const { build } = require("../scripts/build");
5
+
6
+ async function main() {
7
+ await build();
8
+ }
9
+
10
+ main();
@@ -0,0 +1,12 @@
1
+ import * as React from 'react';
2
+ type WrapperProps = {
3
+ propsUpdateListener: HTMLElement;
4
+ };
5
+ export type Config = {
6
+ extendedProps?: (props: any) => any;
7
+ };
8
+ export declare function embedComponent(InnerComponent: React.ComponentType, config: Config): {
9
+ ({ propsUpdateListener, ...props }: WrapperProps): React.JSX.Element;
10
+ displayName: string;
11
+ };
12
+ export {};
@@ -0,0 +1,15 @@
1
+ import * as React from 'react';
2
+ export type Config<T> = {
3
+ initialState: T;
4
+ inputs: any;
5
+ events: Record<string, EmbeddableEvent<T>>;
6
+ };
7
+ export type EmbeddableEvent<T> = (value: T, setter: Setter<T>) => void;
8
+ type Setter<T> = (value: T) => void;
9
+ export declare function embedEditor<T>(InnerComponent: React.ComponentType, config: Config<T>): {
10
+ ({ editorId }: {
11
+ editorId: any;
12
+ }): React.JSX.Element;
13
+ displayName: string;
14
+ };
15
+ export {};
@@ -0,0 +1,123 @@
1
+ 'use strict';
2
+
3
+ var React = require('react');
4
+
5
+ function _interopNamespaceDefault(e) {
6
+ var n = Object.create(null);
7
+ if (e) {
8
+ Object.keys(e).forEach(function (k) {
9
+ if (k !== 'default') {
10
+ var d = Object.getOwnPropertyDescriptor(e, k);
11
+ Object.defineProperty(n, k, d.get ? d : {
12
+ enumerable: true,
13
+ get: function () { return e[k]; }
14
+ });
15
+ }
16
+ });
17
+ }
18
+ n.default = e;
19
+ return Object.freeze(n);
20
+ }
21
+
22
+ var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React);
23
+
24
+ /******************************************************************************
25
+ Copyright (c) Microsoft Corporation.
26
+
27
+ Permission to use, copy, modify, and/or distribute this software for any
28
+ purpose with or without fee is hereby granted.
29
+
30
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
31
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
32
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
33
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
34
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
35
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
36
+ PERFORMANCE OF THIS SOFTWARE.
37
+ ***************************************************************************** */
38
+ /* global Reflect, Promise, SuppressedError, Symbol */
39
+
40
+
41
+ var __assign = function() {
42
+ __assign = Object.assign || function __assign(t) {
43
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
44
+ s = arguments[i];
45
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
46
+ }
47
+ return t;
48
+ };
49
+ return __assign.apply(this, arguments);
50
+ };
51
+
52
+ function __rest(s, e) {
53
+ var t = {};
54
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
55
+ t[p] = s[p];
56
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
57
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
58
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
59
+ t[p[i]] = s[p[i]];
60
+ }
61
+ return t;
62
+ }
63
+
64
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
65
+ var e = new Error(message);
66
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
67
+ };
68
+
69
+ var EVENT_NAME = 'embeddable-event:update-props';
70
+ function embedComponent(InnerComponent, config) {
71
+ var _a;
72
+ function EmbeddableWrapper(_a) {
73
+ var propsUpdateListener = _a.propsUpdateListener, props = __rest(_a, ["propsUpdateListener"]);
74
+ var _b = React__namespace.useState(props), propsProxy = _b[0], setProps = _b[1];
75
+ var propsUpdateEventHandler = function (_a) {
76
+ var detail = _a.detail;
77
+ return setProps(detail);
78
+ };
79
+ React__namespace.useEffect(function () {
80
+ propsUpdateListener.addEventListener(EVENT_NAME, propsUpdateEventHandler);
81
+ return function () { return propsUpdateListener.removeEventListener(EVENT_NAME, propsUpdateEventHandler); };
82
+ }, []);
83
+ var extendedProps = React__namespace.useMemo(function () { var _a; return (_a = config === null || config === void 0 ? void 0 : config.extendedProps) === null || _a === void 0 ? void 0 : _a.call(config, propsProxy); }, [propsProxy, config === null || config === void 0 ? void 0 : config.extendedProps]);
84
+ return React__namespace.createElement(InnerComponent, __assign({}, propsProxy, extendedProps));
85
+ }
86
+ EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : 'Component', ")");
87
+ return EmbeddableWrapper;
88
+ }
89
+
90
+ function embedEditor(InnerComponent, config) {
91
+ var _a;
92
+ function EmbeddableWrapper(_a) {
93
+ var editorId = _a.editorId;
94
+ var _b = React__namespace.useState(config.initialState), componentState = _b[0], setComponentState = _b[1];
95
+ var createEvent = function (value, eventName) {
96
+ var event = new CustomEvent("".concat(editorId, ":").concat(eventName), {
97
+ bubbles: false,
98
+ detail: value,
99
+ });
100
+ window.dispatchEvent(event);
101
+ };
102
+ var events = config.events;
103
+ var eventProps = {};
104
+ var _loop_1 = function (event_1) {
105
+ if (events.hasOwnProperty(event_1)) {
106
+ var eventFunction_1 = events[event_1];
107
+ eventProps[event_1] = function (value) {
108
+ eventFunction_1(value, setComponentState);
109
+ createEvent(value, event_1);
110
+ };
111
+ }
112
+ };
113
+ for (var event_1 in events) {
114
+ _loop_1(event_1);
115
+ }
116
+ return React__namespace.createElement(InnerComponent, __assign({}, eventProps, { state: componentState }, config.inputs));
117
+ }
118
+ EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : 'Editor', ")");
119
+ return EmbeddableWrapper;
120
+ }
121
+
122
+ exports.embedComponent = embedComponent;
123
+ exports.embedEditor = embedEditor;
package/lib/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { embedComponent } from './embedComponent';
2
+ export { embedEditor } from './embedEditor';
@@ -0,0 +1,101 @@
1
+ import * as React from 'react';
2
+
3
+ /******************************************************************************
4
+ Copyright (c) Microsoft Corporation.
5
+
6
+ Permission to use, copy, modify, and/or distribute this software for any
7
+ purpose with or without fee is hereby granted.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
14
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
16
+ ***************************************************************************** */
17
+ /* global Reflect, Promise, SuppressedError, Symbol */
18
+
19
+
20
+ var __assign = function() {
21
+ __assign = Object.assign || function __assign(t) {
22
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
23
+ s = arguments[i];
24
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
25
+ }
26
+ return t;
27
+ };
28
+ return __assign.apply(this, arguments);
29
+ };
30
+
31
+ function __rest(s, e) {
32
+ var t = {};
33
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
34
+ t[p] = s[p];
35
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
36
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
37
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
38
+ t[p[i]] = s[p[i]];
39
+ }
40
+ return t;
41
+ }
42
+
43
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
44
+ var e = new Error(message);
45
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
46
+ };
47
+
48
+ var EVENT_NAME = 'embeddable-event:update-props';
49
+ function embedComponent(InnerComponent, config) {
50
+ var _a;
51
+ function EmbeddableWrapper(_a) {
52
+ var propsUpdateListener = _a.propsUpdateListener, props = __rest(_a, ["propsUpdateListener"]);
53
+ var _b = React.useState(props), propsProxy = _b[0], setProps = _b[1];
54
+ var propsUpdateEventHandler = function (_a) {
55
+ var detail = _a.detail;
56
+ return setProps(detail);
57
+ };
58
+ React.useEffect(function () {
59
+ propsUpdateListener.addEventListener(EVENT_NAME, propsUpdateEventHandler);
60
+ return function () { return propsUpdateListener.removeEventListener(EVENT_NAME, propsUpdateEventHandler); };
61
+ }, []);
62
+ var extendedProps = React.useMemo(function () { var _a; return (_a = config === null || config === void 0 ? void 0 : config.extendedProps) === null || _a === void 0 ? void 0 : _a.call(config, propsProxy); }, [propsProxy, config === null || config === void 0 ? void 0 : config.extendedProps]);
63
+ return React.createElement(InnerComponent, __assign({}, propsProxy, extendedProps));
64
+ }
65
+ EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : 'Component', ")");
66
+ return EmbeddableWrapper;
67
+ }
68
+
69
+ function embedEditor(InnerComponent, config) {
70
+ var _a;
71
+ function EmbeddableWrapper(_a) {
72
+ var editorId = _a.editorId;
73
+ var _b = React.useState(config.initialState), componentState = _b[0], setComponentState = _b[1];
74
+ var createEvent = function (value, eventName) {
75
+ var event = new CustomEvent("".concat(editorId, ":").concat(eventName), {
76
+ bubbles: false,
77
+ detail: value,
78
+ });
79
+ window.dispatchEvent(event);
80
+ };
81
+ var events = config.events;
82
+ var eventProps = {};
83
+ var _loop_1 = function (event_1) {
84
+ if (events.hasOwnProperty(event_1)) {
85
+ var eventFunction_1 = events[event_1];
86
+ eventProps[event_1] = function (value) {
87
+ eventFunction_1(value, setComponentState);
88
+ createEvent(value, event_1);
89
+ };
90
+ }
91
+ };
92
+ for (var event_1 in events) {
93
+ _loop_1(event_1);
94
+ }
95
+ return React.createElement(InnerComponent, __assign({}, eventProps, { state: componentState }, config.inputs));
96
+ }
97
+ EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : 'Editor', ")");
98
+ return EmbeddableWrapper;
99
+ }
100
+
101
+ export { embedComponent, embedEditor };
@@ -0,0 +1,145 @@
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.embeddableSdkReact = {}));
5
+ })(this, (function (exports) { 'use strict';
6
+
7
+ /******************************************************************************
8
+ Copyright (c) Microsoft Corporation.
9
+
10
+ Permission to use, copy, modify, and/or distribute this software for any
11
+ purpose with or without fee is hereby granted.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
14
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
15
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
16
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
17
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
18
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
19
+ PERFORMANCE OF THIS SOFTWARE.
20
+ ***************************************************************************** */
21
+ /* global Reflect, Promise, SuppressedError, Symbol */
22
+
23
+
24
+ var __assign = function() {
25
+ __assign = Object.assign || function __assign(t) {
26
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
27
+ s = arguments[i];
28
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
29
+ }
30
+ return t;
31
+ };
32
+ return __assign.apply(this, arguments);
33
+ };
34
+
35
+ function __rest(s, e) {
36
+ var t = {};
37
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
38
+ t[p] = s[p];
39
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
40
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
41
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
42
+ t[p[i]] = s[p[i]];
43
+ }
44
+ return t;
45
+ }
46
+
47
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
48
+ var e = new Error(message);
49
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
50
+ };
51
+
52
+ var react = {exports: {}};
53
+
54
+ var react_production_min = {};
55
+
56
+ /**
57
+ * @license React
58
+ * react.production.min.js
59
+ *
60
+ * Copyright (c) Facebook, Inc. and its affiliates.
61
+ *
62
+ * This source code is licensed under the MIT license found in the
63
+ * LICENSE file in the root directory of this source tree.
64
+ */
65
+ var l=Symbol.for("react.element"),n=Symbol.for("react.portal"),p=Symbol.for("react.fragment"),q=Symbol.for("react.strict_mode"),r=Symbol.for("react.profiler"),t=Symbol.for("react.provider"),u=Symbol.for("react.context"),v=Symbol.for("react.forward_ref"),w=Symbol.for("react.suspense"),x=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),z=Symbol.iterator;function A(a){if(null===a||"object"!==typeof a)return null;a=z&&a[z]||a["@@iterator"];return "function"===typeof a?a:null}
66
+ var B={isMounted:function(){return !1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,D={};function E(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B;}E.prototype.isReactComponent={};
67
+ E.prototype.setState=function(a,b){if("object"!==typeof a&&"function"!==typeof a&&null!=a)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,a,b,"setState");};E.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate");};function F(){}F.prototype=E.prototype;function G(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B;}var H=G.prototype=new F;
68
+ H.constructor=G;C(H,E.prototype);H.isPureReactComponent=!0;var I=Array.isArray,J=Object.prototype.hasOwnProperty,K={current:null},L={key:!0,ref:!0,__self:!0,__source:!0};
69
+ function M(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=""+b.key),b)J.call(b,d)&&!L.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1<g){for(var f=Array(g),m=0;m<g;m++)f[m]=arguments[m+2];c.children=f;}if(a&&a.defaultProps)for(d in g=a.defaultProps,g)void 0===c[d]&&(c[d]=g[d]);return {$$typeof:l,type:a,key:k,ref:h,props:c,_owner:K.current}}
70
+ function N(a,b){return {$$typeof:l,type:a.type,key:b,ref:a.ref,props:a.props,_owner:a._owner}}function O(a){return "object"===typeof a&&null!==a&&a.$$typeof===l}function escape(a){var b={"=":"=0",":":"=2"};return "$"+a.replace(/[=:]/g,function(a){return b[a]})}var P=/\/+/g;function Q(a,b){return "object"===typeof a&&null!==a&&null!=a.key?escape(""+a.key):b.toString(36)}
71
+ function R(a,b,e,d,c){var k=typeof a;if("undefined"===k||"boolean"===k)a=null;var h=!1;if(null===a)h=!0;else switch(k){case "string":case "number":h=!0;break;case "object":switch(a.$$typeof){case l:case n:h=!0;}}if(h)return h=a,c=c(h),a=""===d?"."+Q(h,0):d,I(c)?(e="",null!=a&&(e=a.replace(P,"$&/")+"/"),R(c,b,e,"",function(a){return a})):null!=c&&(O(c)&&(c=N(c,e+(!c.key||h&&h.key===c.key?"":(""+c.key).replace(P,"$&/")+"/")+a)),b.push(c)),1;h=0;d=""===d?".":d+":";if(I(a))for(var g=0;g<a.length;g++){k=
72
+ a[g];var f=d+Q(k,g);h+=R(k,b,e,f,c);}else if(f=A(a),"function"===typeof f)for(a=f.call(a),g=0;!(k=a.next()).done;)k=k.value,f=d+Q(k,g++),h+=R(k,b,e,f,c);else if("object"===k)throw b=String(a),Error("Objects are not valid as a React child (found: "+("[object Object]"===b?"object with keys {"+Object.keys(a).join(", ")+"}":b)+"). If you meant to render a collection of children, use an array instead.");return h}
73
+ function S(a,b,e){if(null==a)return a;var d=[],c=0;R(a,d,"","",function(a){return b.call(e,a,c++)});return d}function T(a){if(-1===a._status){var b=a._result;b=b();b.then(function(b){if(0===a._status||-1===a._status)a._status=1,a._result=b;},function(b){if(0===a._status||-1===a._status)a._status=2,a._result=b;});-1===a._status&&(a._status=0,a._result=b);}if(1===a._status)return a._result.default;throw a._result;}
74
+ var U={current:null},V={transition:null},W={ReactCurrentDispatcher:U,ReactCurrentBatchConfig:V,ReactCurrentOwner:K};react_production_min.Children={map:S,forEach:function(a,b,e){S(a,function(){b.apply(this,arguments);},e);},count:function(a){var b=0;S(a,function(){b++;});return b},toArray:function(a){return S(a,function(a){return a})||[]},only:function(a){if(!O(a))throw Error("React.Children.only expected to receive a single React element child.");return a}};react_production_min.Component=E;react_production_min.Fragment=p;
75
+ react_production_min.Profiler=r;react_production_min.PureComponent=G;react_production_min.StrictMode=q;react_production_min.Suspense=w;react_production_min.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=W;
76
+ react_production_min.cloneElement=function(a,b,e){if(null===a||void 0===a)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+a+".");var d=C({},a.props),c=a.key,k=a.ref,h=a._owner;if(null!=b){void 0!==b.ref&&(k=b.ref,h=K.current);void 0!==b.key&&(c=""+b.key);if(a.type&&a.type.defaultProps)var g=a.type.defaultProps;for(f in b)J.call(b,f)&&!L.hasOwnProperty(f)&&(d[f]=void 0===b[f]&&void 0!==g?g[f]:b[f]);}var f=arguments.length-2;if(1===f)d.children=e;else if(1<f){g=Array(f);
77
+ for(var m=0;m<f;m++)g[m]=arguments[m+2];d.children=g;}return {$$typeof:l,type:a.type,key:c,ref:k,props:d,_owner:h}};react_production_min.createContext=function(a){a={$$typeof:u,_currentValue:a,_currentValue2:a,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null};a.Provider={$$typeof:t,_context:a};return a.Consumer=a};react_production_min.createElement=M;react_production_min.createFactory=function(a){var b=M.bind(null,a);b.type=a;return b};react_production_min.createRef=function(){return {current:null}};
78
+ react_production_min.forwardRef=function(a){return {$$typeof:v,render:a}};react_production_min.isValidElement=O;react_production_min.lazy=function(a){return {$$typeof:y,_payload:{_status:-1,_result:a},_init:T}};react_production_min.memo=function(a,b){return {$$typeof:x,type:a,compare:void 0===b?null:b}};react_production_min.startTransition=function(a){var b=V.transition;V.transition={};try{a();}finally{V.transition=b;}};react_production_min.unstable_act=function(){throw Error("act(...) is not supported in production builds of React.");};
79
+ react_production_min.useCallback=function(a,b){return U.current.useCallback(a,b)};react_production_min.useContext=function(a){return U.current.useContext(a)};react_production_min.useDebugValue=function(){};react_production_min.useDeferredValue=function(a){return U.current.useDeferredValue(a)};react_production_min.useEffect=function(a,b){return U.current.useEffect(a,b)};react_production_min.useId=function(){return U.current.useId()};react_production_min.useImperativeHandle=function(a,b,e){return U.current.useImperativeHandle(a,b,e)};
80
+ react_production_min.useInsertionEffect=function(a,b){return U.current.useInsertionEffect(a,b)};react_production_min.useLayoutEffect=function(a,b){return U.current.useLayoutEffect(a,b)};react_production_min.useMemo=function(a,b){return U.current.useMemo(a,b)};react_production_min.useReducer=function(a,b,e){return U.current.useReducer(a,b,e)};react_production_min.useRef=function(a){return U.current.useRef(a)};react_production_min.useState=function(a){return U.current.useState(a)};react_production_min.useSyncExternalStore=function(a,b,e){return U.current.useSyncExternalStore(a,b,e)};
81
+ react_production_min.useTransition=function(){return U.current.useTransition()};react_production_min.version="18.2.0";
82
+
83
+ {
84
+ react.exports = react_production_min;
85
+ }
86
+
87
+ var reactExports = react.exports;
88
+
89
+ var EVENT_NAME = 'embeddable-event:update-props';
90
+ function embedComponent(InnerComponent, config) {
91
+ var _a;
92
+ function EmbeddableWrapper(_a) {
93
+ var propsUpdateListener = _a.propsUpdateListener, props = __rest(_a, ["propsUpdateListener"]);
94
+ var _b = reactExports.useState(props), propsProxy = _b[0], setProps = _b[1];
95
+ var propsUpdateEventHandler = function (_a) {
96
+ var detail = _a.detail;
97
+ return setProps(detail);
98
+ };
99
+ reactExports.useEffect(function () {
100
+ propsUpdateListener.addEventListener(EVENT_NAME, propsUpdateEventHandler);
101
+ return function () { return propsUpdateListener.removeEventListener(EVENT_NAME, propsUpdateEventHandler); };
102
+ }, []);
103
+ var extendedProps = reactExports.useMemo(function () { var _a; return (_a = config === null || config === void 0 ? void 0 : config.extendedProps) === null || _a === void 0 ? void 0 : _a.call(config, propsProxy); }, [propsProxy, config === null || config === void 0 ? void 0 : config.extendedProps]);
104
+ return reactExports.createElement(InnerComponent, __assign({}, propsProxy, extendedProps));
105
+ }
106
+ EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : 'Component', ")");
107
+ return EmbeddableWrapper;
108
+ }
109
+
110
+ function embedEditor(InnerComponent, config) {
111
+ var _a;
112
+ function EmbeddableWrapper(_a) {
113
+ var editorId = _a.editorId;
114
+ var _b = reactExports.useState(config.initialState), componentState = _b[0], setComponentState = _b[1];
115
+ var createEvent = function (value, eventName) {
116
+ var event = new CustomEvent("".concat(editorId, ":").concat(eventName), {
117
+ bubbles: false,
118
+ detail: value,
119
+ });
120
+ window.dispatchEvent(event);
121
+ };
122
+ var events = config.events;
123
+ var eventProps = {};
124
+ var _loop_1 = function (event_1) {
125
+ if (events.hasOwnProperty(event_1)) {
126
+ var eventFunction_1 = events[event_1];
127
+ eventProps[event_1] = function (value) {
128
+ eventFunction_1(value, setComponentState);
129
+ createEvent(value, event_1);
130
+ };
131
+ }
132
+ };
133
+ for (var event_1 in events) {
134
+ _loop_1(event_1);
135
+ }
136
+ return reactExports.createElement(InnerComponent, __assign({}, eventProps, { state: componentState }, config.inputs));
137
+ }
138
+ EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : 'Editor', ")");
139
+ return EmbeddableWrapper;
140
+ }
141
+
142
+ exports.embedComponent = embedComponent;
143
+ exports.embedEditor = embedEditor;
144
+
145
+ }));
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@embeddable.com/sdk-react",
3
+ "version": "0.0.1",
4
+ "description": "TODO.",
5
+ "main": "lib/index.cjs.js",
6
+ "module": "lib/index.esm.js",
7
+ "browser": "lib/index.umd.js",
8
+ "types": "lib/index.d.ts",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/embeddable-hq/embeddable-sdk.git",
12
+ "directory": "packages/react"
13
+ },
14
+ "scripts": {
15
+ "build": "rollup -c"
16
+ },
17
+ "bin": {
18
+ "embeddable-react": "bin/embeddable-react"
19
+ },
20
+ "author": "Oleg Kapustin <oleg@trevor.io>",
21
+ "license": "MIT",
22
+ "peerDependencies": {
23
+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0"
24
+ },
25
+ "devDependencies": {
26
+ "@rollup/plugin-commonjs": "^25.0.2",
27
+ "@rollup/plugin-node-resolve": "^15.1.0",
28
+ "@rollup/plugin-replace": "^5.0.2",
29
+ "@rollup/plugin-typescript": "^11.1.2",
30
+ "@types/react": "^18.2.14",
31
+ "react": "^18.2.0",
32
+ "rollup": "^3.26.0",
33
+ "typescript": "^5.1.6"
34
+ },
35
+ "dependencies": {
36
+ "@embeddable-sdk/core": "*",
37
+ "@vitejs/plugin-react": "^4.0.2",
38
+ "ora": "^6.3.1",
39
+ "vite": "^4.4.2"
40
+ }
41
+ }
@@ -0,0 +1,36 @@
1
+ import typescript from '@rollup/plugin-typescript';
2
+ import resolve from '@rollup/plugin-node-resolve';
3
+ import commonjs from '@rollup/plugin-commonjs';
4
+ import replace from '@rollup/plugin-replace';
5
+ import pkg from './package.json' assert { type: 'json' };
6
+
7
+ export default [
8
+ {
9
+ input: './src/index.ts',
10
+ output: {
11
+ name: 'embeddableSdkReact',
12
+ file: pkg.browser,
13
+ format: 'umd'
14
+ },
15
+ plugins: [
16
+ replace({
17
+ preventAssignment: true,
18
+ values: {
19
+ 'process.env.NODE_ENV': JSON.stringify('production')
20
+ }
21
+ }),
22
+ resolve(),
23
+ commonjs(),
24
+ typescript()
25
+ ],
26
+ },
27
+ {
28
+ input: './src/index.ts',
29
+ external: Object.keys(pkg.peerDependencies),
30
+ output: [
31
+ { file: pkg.main, format: 'cjs' },
32
+ { file: pkg.module, format: 'es' }
33
+ ],
34
+ plugins: [typescript()]
35
+ }
36
+ ]
@@ -0,0 +1,40 @@
1
+ const path = require("path");
2
+ const { fork } = require('child_process');
3
+ const oraP = import('ora');
4
+
5
+ const {createContext} = require("./createContext");
6
+ const {prepare} = require("./prepare");
7
+ const {cleanup} = require("./cleanup");
8
+
9
+ const generateFork = fork(path.resolve(__dirname, 'generate.js'), [], { silent: true });
10
+
11
+ async function build() {
12
+ const ora = (await oraP).default; // TODO: migrate cli to modules/ts and bundle.
13
+
14
+ const spinnerPrepare = ora("preparation").start();
15
+
16
+ const ctx = createContext(path.resolve(__dirname, '..'), process.cwd());
17
+
18
+ await validationEmulation();
19
+ await prepare(ctx);
20
+ spinnerPrepare.succeed();
21
+
22
+ const spinnerBuild = ora("build").start();
23
+
24
+ generateFork.send({ ctx });
25
+
26
+ generateFork.on('exit', async () => {
27
+ await cleanup(ctx);
28
+ spinnerBuild.succeed();
29
+ })
30
+
31
+ }
32
+
33
+ module.exports = { build };
34
+
35
+ // TODO: later we will validate configs e.g. yaml files with this function.
36
+ function validationEmulation() {
37
+ return new Promise((res, rej) => {
38
+ setTimeout(res, 4000);
39
+ })
40
+ }
@@ -0,0 +1,8 @@
1
+ const fs = require("fs/promises");
2
+ const path = require("path");
3
+
4
+ async function cleanup(ctx) {
5
+ await fs.rm(path.resolve(ctx.client.rootDir, 'embeddable-entry-point.jsx'));
6
+ }
7
+
8
+ module.exports = { cleanup };
@@ -0,0 +1,21 @@
1
+ const path = require('path');
2
+
3
+ function createContext (pluginRoot, clientRoot) {
4
+ return {
5
+ plugin: {
6
+ rootDir: pluginRoot,
7
+ templatesDir: path.resolve(pluginRoot, 'templates'),
8
+ },
9
+ client: {
10
+ rootDir: clientRoot,
11
+ srcDir: path.resolve(clientRoot, 'src'), // TODO: should be specified via command parameters or from rc file.
12
+ buildDir: path.resolve(clientRoot, '.embeddable-build')
13
+ },
14
+ outputOptions: { // TODO: should be specified via command parameters or from rc file.
15
+ fileName: 'embeddable-prepared',
16
+ buildName: 'embeddable-prepared-build',
17
+ },
18
+ };
19
+ }
20
+
21
+ module.exports = { createContext };
@@ -0,0 +1,99 @@
1
+ const fs = require("fs/promises");
2
+ const path = require("path");
3
+ const vite = require("vite");
4
+ const viteReactPlugin = require('@vitejs/plugin-react');
5
+ const core = require("@embeddable-sdk/core/src/build");
6
+
7
+ process.on('message', async ({ ctx }) => {
8
+ await generate(ctx);
9
+
10
+ process.exit();
11
+ });
12
+
13
+ async function generate(ctx) {
14
+ const filesList = await findEmbFiles(ctx.client.srcDir);
15
+
16
+ await injectImports(ctx, filesList);
17
+
18
+ await runViteBuild(ctx);
19
+
20
+ await runCoreBuild(ctx);
21
+ }
22
+
23
+ module.exports = { generate };
24
+
25
+
26
+ async function runCoreBuild(ctx) {
27
+ await core.build({
28
+ outDir: ctx.outputOptions.buildName,
29
+ renderFunctionFileName: ctx.outputOptions.fileName
30
+ });
31
+ }
32
+
33
+ async function runViteBuild(ctx) {
34
+ process.chdir(ctx.client.rootDir);
35
+
36
+ await vite.build({
37
+ plugins: [viteReactPlugin()],
38
+ build: {
39
+ lib: {
40
+ entry: './embeddable-entry-point.jsx',
41
+ formats: ['es'],
42
+ fileName: ctx.outputOptions.fileName
43
+ },
44
+ outDir: `.embeddable-build/${ctx.outputOptions.buildName}`
45
+ },
46
+ define: { 'process.env.NODE_ENV': '"production"' }
47
+ });
48
+ }
49
+
50
+
51
+ const REPLACE_TOKEN = '{{LAZY_IMPORTS}}';
52
+
53
+ async function injectImports(ctx, filesList) {
54
+ const imports = filesList.map(([fileName, filePath]) =>
55
+ `\t${fileName}: React.lazy(() => import('./${path.relative(ctx.client.rootDir, filePath)}'))`
56
+ ).join(',\n');
57
+
58
+ const content = await fs.readFile(
59
+ path.resolve(ctx.plugin.templatesDir, 'embeddable-entry-point.jsx.template'),
60
+ 'utf8'
61
+ );
62
+
63
+ await fs.writeFile(
64
+ path.resolve(ctx.client.rootDir, 'embeddable-entry-point.jsx'),
65
+ content.replace(REPLACE_TOKEN, imports)
66
+ );
67
+ }
68
+
69
+
70
+ const EMB_FILE_REGEX = /^(.*)\.emb\.(j|t)s$/;
71
+
72
+ async function findEmbFiles (initialSrcDir) {
73
+ const filesList = [];
74
+
75
+ async function findEmbFilesRec(srcDir) {
76
+ const allFiles = await fs.readdir(srcDir);
77
+
78
+ for (const file of allFiles) {
79
+ const filePath = path.join(srcDir, file)
80
+
81
+ const status = await fs.lstat(filePath);
82
+
83
+ if (status.isDirectory()) {
84
+ await findEmbFilesRec(filePath)
85
+ }
86
+
87
+ const fileName = file.match(EMB_FILE_REGEX);
88
+
89
+ if (fileName) {
90
+ filesList.push([fileName[1], filePath]);
91
+ }
92
+ }
93
+ }
94
+
95
+ await findEmbFilesRec(initialSrcDir);
96
+
97
+
98
+ return filesList;
99
+ }
@@ -0,0 +1,13 @@
1
+ const fsSync = require("fs");
2
+ const fs = require("fs/promises");
3
+
4
+ async function prepare (ctx) {
5
+ await removeIfExists(ctx.client.buildDir);
6
+ }
7
+
8
+ module.exports = { prepare }
9
+
10
+ async function removeIfExists(buildDir) {
11
+ if (fsSync.existsSync(buildDir)) await fs.rm(buildDir, { recursive: true });
12
+ }
13
+
@@ -0,0 +1,40 @@
1
+ import * as React from 'react';
2
+
3
+ type WrapperProps = {
4
+ propsUpdateListener: HTMLElement
5
+ };
6
+
7
+ const EVENT_NAME = 'embeddable-event:update-props';
8
+
9
+ // TODO: define config type.
10
+ export type Config = {
11
+ extendedProps?: (props: any) => any
12
+ };
13
+
14
+ export function embedComponent(InnerComponent: React.ComponentType, config: Config) {
15
+ function EmbeddableWrapper({propsUpdateListener, ...props}: WrapperProps) {
16
+ const [propsProxy, setProps] = React.useState(props);
17
+
18
+ const propsUpdateEventHandler = ({ detail }: CustomEvent<typeof propsProxy>) => setProps(detail);
19
+
20
+
21
+ React.useEffect(() => {
22
+ propsUpdateListener.addEventListener(EVENT_NAME, propsUpdateEventHandler);
23
+
24
+ return () => propsUpdateListener.removeEventListener(EVENT_NAME, propsUpdateEventHandler);
25
+ }, []);
26
+
27
+
28
+ const extendedProps = React.useMemo(
29
+ () => config?.extendedProps?.(propsProxy),
30
+ [propsProxy, config?.extendedProps]
31
+ );
32
+
33
+ return <InnerComponent {...propsProxy} {...extendedProps}/>;
34
+ }
35
+
36
+ EmbeddableWrapper.displayName = `embedded(${InnerComponent.displayName ?? 'Component'})`;
37
+
38
+
39
+ return EmbeddableWrapper;
40
+ }
@@ -0,0 +1,48 @@
1
+ import * as React from 'react';
2
+
3
+ export type Config<T> = {
4
+ initialState: T
5
+ inputs: any;
6
+ events: Record<string, EmbeddableEvent<T>>
7
+ };
8
+
9
+ export type EmbeddableEvent<T> = (value: T, setter: Setter<T>) => void;
10
+
11
+ type Setter<T> = (value: T) => void;
12
+
13
+ export function embedEditor<T>(InnerComponent: React.ComponentType, config: Config<T>) {
14
+
15
+ function EmbeddableWrapper({editorId}) {
16
+
17
+ const [componentState, setComponentState] = React.useState(config.initialState);
18
+
19
+ const createEvent = (value: T, eventName) => {
20
+
21
+ const event = new CustomEvent(`${editorId}:${eventName}`, {
22
+ bubbles: false,
23
+ detail: value,
24
+ });
25
+ window.dispatchEvent(event);
26
+ }
27
+
28
+ const events = config.events;
29
+ const eventProps: Record<string, (value: T) => void> = {};
30
+
31
+ for (const event in events) {
32
+ if (events.hasOwnProperty(event)) {
33
+ let eventFunction = events[event];
34
+ eventProps[event] = (value: T) => {
35
+ eventFunction(value, setComponentState)
36
+ createEvent(value, event)
37
+ }
38
+ }
39
+ }
40
+
41
+ return <InnerComponent {...eventProps} state={componentState} {...config.inputs} />;
42
+ }
43
+
44
+ EmbeddableWrapper.displayName = `embedded(${InnerComponent.displayName ?? 'Editor'})`;
45
+
46
+
47
+ return EmbeddableWrapper;
48
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export { connectWidget } from './connectWidget';
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export { embedComponent } from './embedComponent';
2
+ export { embedEditor } from './embedEditor';
@@ -0,0 +1,17 @@
1
+ import 'vite/modulepreload-polyfill';
2
+
3
+ import React from 'react';
4
+ import ReactDOM from 'react-dom/client';
5
+
6
+ const COMPONENT_MAP = {
7
+ {{LAZY_IMPORTS}}
8
+ };
9
+
10
+ export default (rootEl, componentName, props) => {
11
+ const Component = COMPONENT_MAP[componentName]
12
+ ReactDOM.createRoot(rootEl).render(
13
+ <React.Suspense fallback={<div/>}>
14
+ <Component {...props} propsUpdateListener={rootEl} />
15
+ </React.Suspense>
16
+ )
17
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "include": ["src/**/*"],
3
+ "compilerOptions": {
4
+ "module": "esnext",
5
+ "target": "es5",
6
+ "skipLibCheck": true,
7
+ "jsx": "react",
8
+ "sourceMap": true,
9
+ "declaration": true,
10
+ "outDir": "lib"
11
+ },
12
+ "exclude": [
13
+ "node_modules",
14
+ "lib"
15
+ ]
16
+ }