@embeddable.com/sdk-react 1.0.0 → 2.0.0

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.
package/lib/index.cjs.js CHANGED
@@ -1,7 +1,13 @@
1
1
  'use strict';
2
2
 
3
- var React = require('react');
4
- var sdkCore = require('@embeddable.com/sdk-core');
3
+ var path = require('node:path');
4
+ var fs = require('fs/promises');
5
+ var path$1 = require('path');
6
+ var vite = require('vite');
7
+ var viteReactPlugin = require('@vitejs/plugin-react');
8
+ var extractComponentsConfigPlugin = require('@embeddable.com/extract-components-config');
9
+ var sdkUtils = require('@embeddable.com/sdk-utils');
10
+ var promises = require('node:fs/promises');
5
11
 
6
12
  function _interopNamespaceDefault(e) {
7
13
  var n = Object.create(null);
@@ -20,218 +26,91 @@ function _interopNamespaceDefault(e) {
20
26
  return Object.freeze(n);
21
27
  }
22
28
 
23
- var React__namespace = /*#__PURE__*/_interopNamespaceDefault(React);
29
+ var path__namespace$1 = /*#__PURE__*/_interopNamespaceDefault(path);
30
+ var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs);
31
+ var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path$1);
32
+ var vite__namespace = /*#__PURE__*/_interopNamespaceDefault(vite);
24
33
 
25
- /******************************************************************************
26
- Copyright (c) Microsoft Corporation.
27
-
28
- Permission to use, copy, modify, and/or distribute this software for any
29
- purpose with or without fee is hereby granted.
30
-
31
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
32
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
33
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
34
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
35
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
36
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
37
- PERFORMANCE OF THIS SOFTWARE.
38
- ***************************************************************************** */
39
- /* global Reflect, Promise, SuppressedError, Symbol */
40
-
41
-
42
- var __assign = function() {
43
- __assign = Object.assign || function __assign(t) {
44
- for (var s, i = 1, n = arguments.length; i < n; i++) {
45
- s = arguments[i];
46
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
47
- }
48
- return t;
49
- };
50
- return __assign.apply(this, arguments);
51
- };
52
-
53
- function __rest(s, e) {
54
- var t = {};
55
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
56
- t[p] = s[p];
57
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
58
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
59
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
60
- t[p[i]] = s[p[i]];
61
- }
62
- return t;
63
- }
64
-
65
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
66
- var e = new Error(message);
67
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
34
+ var createContext = (pluginRoot, coreCtx) => {
35
+ coreCtx["sdk-react"] = {
36
+ rootDir: pluginRoot,
37
+ templatesDir: path.resolve(pluginRoot, "templates"),
38
+ outputOptions: {
39
+ fileName: "embeddable-prepared",
40
+ buildName: "embeddable-prepared-build",
41
+ componentsEntryPointFilename: "embeddable-entry-point.jsx",
42
+ },
43
+ };
68
44
  };
69
45
 
70
- var EmbeddableStateContext = React__namespace.createContext({});
71
- var useEmbeddableState = function (initialState) {
72
- if (initialState === void 0) { initialState = {}; }
73
- var ctx = React__namespace.useContext(EmbeddableStateContext);
74
- React__namespace.useEffect(function () {
75
- ctx[1](initialState);
76
- }, [initialState]);
77
- return ctx;
46
+ const oraP = import('ora');
47
+ const EMB_FILE_REGEX = /^(.*)(?<!\.type|\.options)\.emb\.[jt]s$/;
48
+ const EMB_TYPE_FILE_REGEX = /^(.*)\.type\.emb\.[jt]s$/;
49
+ var generate = async (ctx) => {
50
+ const ora = (await oraP).default;
51
+ const progress = ora("React: building components...").start();
52
+ const filesList = await sdkUtils.findFiles(ctx.client.srcDir, EMB_FILE_REGEX);
53
+ await injectImports(ctx, filesList);
54
+ await runViteBuild(ctx);
55
+ progress.succeed("React: components built completed");
78
56
  };
57
+ async function runViteBuild(ctx) {
58
+ process.chdir(ctx.client.rootDir);
59
+ await vite__namespace.build({
60
+ logLevel: "error",
61
+ plugins: [
62
+ viteReactPlugin(),
63
+ extractComponentsConfigPlugin({
64
+ globalKey: "componentsMeta",
65
+ fileName: "embeddable-components-meta.js",
66
+ outputDir: ".embeddable-build",
67
+ componentFileRegex: EMB_FILE_REGEX,
68
+ typeFileRegex: EMB_TYPE_FILE_REGEX,
69
+ searchEntry: "embedComponent",
70
+ }),
71
+ extractComponentsConfigPlugin({
72
+ globalKey: "editorsMeta",
73
+ fileName: "embeddable-editors-meta.js",
74
+ outputDir: ".embeddable-build",
75
+ componentFileRegex: EMB_FILE_REGEX,
76
+ typeFileRegex: EMB_TYPE_FILE_REGEX,
77
+ searchEntry: "embedControl",
78
+ }),
79
+ ],
80
+ build: {
81
+ lib: {
82
+ entry: `./${ctx["sdk-react"].outputOptions.componentsEntryPointFilename}`,
83
+ formats: ["es"],
84
+ fileName: ctx["sdk-react"].outputOptions.fileName,
85
+ },
86
+ outDir: `.embeddable-build/${ctx["sdk-react"].outputOptions.buildName}`,
87
+ },
88
+ define: { "process.env.NODE_ENV": '"production"' },
89
+ });
90
+ }
91
+ const REPLACE_TOKEN = "{{LAZY_IMPORTS}}";
92
+ async function injectImports(ctx, filesList) {
93
+ const imports = filesList
94
+ .map(([fileName, filePath]) => `\t${fileName}: React.lazy(() => import('./${path__namespace.relative(ctx.client.rootDir, filePath)}'))`)
95
+ .join(",\n");
96
+ const content = await fs__namespace.readFile(path__namespace.resolve(ctx["sdk-react"].templatesDir, `${ctx["sdk-react"].outputOptions.componentsEntryPointFilename}.template`), "utf8");
97
+ await fs__namespace.writeFile(path__namespace.resolve(ctx.client.rootDir, ctx["sdk-react"].outputOptions.componentsEntryPointFilename), content.replace(REPLACE_TOKEN, imports));
98
+ }
79
99
 
80
- var UPDATE_PROPS_EVENT_NAME = "embeddable-event:update-props";
81
- var RELOAD_DATASET_EVENT_NAME = "embeddable-event:reload-dataset";
82
- var LOAD_DATA_RESULT_EVENT_NAME = "embeddable-event:load-data-result";
83
- var ReducerActionTypes = {
84
- loading: "loading",
85
- error: "error",
86
- data: "data",
87
- };
88
- var reducer = function (state, action) {
89
- var _a, _b, _c;
90
- switch (action.type) {
91
- case ReducerActionTypes.loading: {
92
- return __assign(__assign({}, state), (_a = {}, _a[action.inputName] = {
93
- data: state[action.inputName].data,
94
- isLoading: true,
95
- }, _a));
96
- }
97
- case ReducerActionTypes.data: {
98
- return __assign(__assign({}, state), (_b = {}, _b[action.inputName] = { isLoading: false, data: action.payload }, _b));
99
- }
100
- case ReducerActionTypes.error: {
101
- return __assign(__assign({}, state), (_c = {}, _c[action.inputName] = {
102
- isLoading: false,
103
- error: action.payload.message || action.payload,
104
- }, _c));
105
- }
106
- }
107
- return state;
100
+ var build = async (ctx) => {
101
+ createContext(path__namespace$1.resolve(__dirname, ".."), ctx);
102
+ await generate(ctx);
108
103
  };
109
- var createInitialLoadersState = function (dataLoaders) {
110
- return Object.keys(dataLoaders).reduce(function (loaderState, loaderKey) {
111
- var _a;
112
- return (__assign(__assign({}, loaderState), (_a = {}, _a[loaderKey] = { isLoading: false }, _a)));
113
- }, {});
114
- };
115
- function embedComponent(InnerComponent, config) {
116
- var _a;
117
- if (config === void 0) { config = {}; }
118
- function EmbeddableWrapper(_a) {
119
- var propsUpdateListener = _a.propsUpdateListener, props = __rest(_a, ["propsUpdateListener"]);
120
- var _b = React__namespace.useState(props), propsProxy = _b[0], setProps = _b[1];
121
- var embeddableState = React__namespace.useState();
122
- var componentId = props.componentId;
123
- var loadDataResultEventName = "".concat(LOAD_DATA_RESULT_EVENT_NAME, ":").concat(componentId);
124
- var propsUpdateEventHandler = function (_a) {
125
- var detail = _a.detail;
126
- return setProps(detail);
127
- };
128
- React__namespace.useEffect(function () {
129
- propsUpdateListener.addEventListener(UPDATE_PROPS_EVENT_NAME, propsUpdateEventHandler);
130
- return function () {
131
- return propsUpdateListener.removeEventListener(UPDATE_PROPS_EVENT_NAME, propsUpdateEventHandler);
132
- };
133
- }, []);
134
- var _c = React__namespace.useMemo(function () {
135
- var _a, _b;
136
- return Object.entries((_b = (_a = config === null || config === void 0 ? void 0 : config.props) === null || _a === void 0 ? void 0 : _a.call(config, propsProxy, embeddableState)) !== null && _b !== void 0 ? _b : {}).reduce(function (acc, _a) {
137
- var key = _a[0], value = _a[1];
138
- if (sdkCore.isLoadDataParams(value)) {
139
- acc.dataLoaders[key] = value;
140
- }
141
- else {
142
- acc.extendedProps[key] = value;
143
- }
144
- return acc;
145
- }, { extendedProps: {}, dataLoaders: {} });
146
- }, [propsProxy, config === null || config === void 0 ? void 0 : config.props, embeddableState[0]]), extendedProps = _c.extendedProps, dataLoaders = _c.dataLoaders;
147
- var _d = React__namespace.useReducer(reducer, dataLoaders, createInitialLoadersState), loadersState = _d[0], dispatch = _d[1];
148
- var handleDataLoaded = function (inputName, data) {
149
- return dispatch({ type: ReducerActionTypes.data, inputName: inputName, payload: data });
150
- };
151
- var handleError = function (inputName, error) {
152
- return dispatch({ type: ReducerActionTypes.error, inputName: inputName, payload: error });
153
- };
154
- var reloadDataset = function (inputName, params) {
155
- dispatch({ type: ReducerActionTypes.loading, inputName: inputName });
156
- var error = params.dataLoader(params.requestParams, componentId, inputName);
157
- if (error)
158
- handleError(inputName, error);
159
- };
160
- var handleLoadDataResult = function (ev) {
161
- if (ev.detail.isSuccess) {
162
- handleDataLoaded(ev.detail.propertyName, ev.detail.data);
163
- }
164
- else {
165
- handleError(ev.detail.propertyName, ev.detail.error);
166
- }
167
- };
168
- var variableChangedEventHandler = function (_a) {
169
- var detail = _a.detail;
170
- Object.entries(dataLoaders)
171
- .filter(function (_a) {
172
- _a[0]; var params = _a[1];
173
- return params.requestParams.from.datasetId === detail.datasetId;
174
- })
175
- .forEach(function (_a) {
176
- var inputName = _a[0], params = _a[1];
177
- return reloadDataset(inputName, params);
178
- });
179
- };
180
- React__namespace.useEffect(function () {
181
- Object.entries(dataLoaders).forEach(function (_a) {
182
- var inputName = _a[0], params = _a[1];
183
- return reloadDataset(inputName, params);
184
- });
185
- window.addEventListener(RELOAD_DATASET_EVENT_NAME, variableChangedEventHandler);
186
- window.addEventListener(loadDataResultEventName, handleLoadDataResult);
187
- return function () {
188
- window.removeEventListener(RELOAD_DATASET_EVENT_NAME, variableChangedEventHandler);
189
- window.removeEventListener(loadDataResultEventName, handleLoadDataResult);
190
- };
191
- }, [
192
- JSON.stringify(Object.values(dataLoaders).map(function (loader) { return loader.requestParams; })),
193
- ]);
194
- var createEvent = function (value, eventName) {
195
- return sdkCore.setValue(value, componentId, eventName);
196
- };
197
- var events = config === null || config === void 0 ? void 0 : config.events;
198
- var eventProps = {};
199
- if (events) {
200
- var _loop_1 = function (event_1) {
201
- if (events.hasOwnProperty(event_1)) {
202
- var eventFunction_1 = events[event_1];
203
- eventProps[event_1] = function (value) {
204
- return createEvent(eventFunction_1(value), event_1);
205
- };
206
- }
207
- };
208
- for (var event_1 in events) {
209
- _loop_1(event_1);
210
- }
211
- }
212
- return (React__namespace.createElement(EmbeddableStateContext.Provider, { value: embeddableState },
213
- React__namespace.createElement(InnerComponent, __assign({}, extendedProps, eventProps, loadersState))));
214
- }
215
- EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : "Component", ")");
216
- return EmbeddableWrapper;
217
- }
218
104
 
219
- function embedControl(InnerComponent, config) {
220
- var _a;
221
- function EmbeddableWrapper(props) {
222
- var _a, _b;
223
- var componentId = props.componentId, initialValue = props.initialValue;
224
- var _c = React__namespace.useState(initialValue), componentState = _c[0], setComponentState = _c[1];
225
- var setter = function (value) {
226
- setComponentState(value);
227
- sdkCore.setValue(value, componentId);
228
- };
229
- return (React__namespace.createElement(InnerComponent, __assign({}, config.inputs(componentState, setter), ((_b = (_a = config.mapProps) === null || _a === void 0 ? void 0 : _a.call(config, props)) !== null && _b !== void 0 ? _b : {}))));
230
- }
231
- EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : "Editor", ")");
232
- return EmbeddableWrapper;
233
- }
105
+ var cleanup = async (ctx) => await promises.rm(path.resolve(ctx.client.rootDir, ctx["sdk-react"].outputOptions.componentsEntryPointFilename));
106
+
107
+ var index = (coreCtx) => {
108
+ return {
109
+ pluginName: "sdk-react",
110
+ validate: async () => { },
111
+ build,
112
+ cleanup,
113
+ };
114
+ };
234
115
 
235
- exports.embedComponent = embedComponent;
236
- exports.embedControl = embedControl;
237
- exports.useEmbeddableState = useEmbeddableState;
116
+ module.exports = index;
package/lib/index.esm.js CHANGED
@@ -1,214 +1,93 @@
1
- import * as React from 'react';
2
- import { isLoadDataParams, setValue } from '@embeddable.com/sdk-core';
1
+ import * as path$1 from 'node:path';
2
+ import { resolve } from 'node:path';
3
+ import * as fs from 'fs/promises';
4
+ import * as path from 'path';
5
+ import * as vite from 'vite';
6
+ import viteReactPlugin from '@vitejs/plugin-react';
7
+ import extractComponentsConfigPlugin from '@embeddable.com/extract-components-config';
8
+ import { findFiles } from '@embeddable.com/sdk-utils';
9
+ import { rm } from 'node:fs/promises';
3
10
 
4
- /******************************************************************************
5
- Copyright (c) Microsoft Corporation.
6
-
7
- Permission to use, copy, modify, and/or distribute this software for any
8
- purpose with or without fee is hereby granted.
9
-
10
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
11
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
12
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
13
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
14
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
15
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
16
- PERFORMANCE OF THIS SOFTWARE.
17
- ***************************************************************************** */
18
- /* global Reflect, Promise, SuppressedError, Symbol */
19
-
20
-
21
- var __assign = function() {
22
- __assign = Object.assign || function __assign(t) {
23
- for (var s, i = 1, n = arguments.length; i < n; i++) {
24
- s = arguments[i];
25
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
26
- }
27
- return t;
28
- };
29
- return __assign.apply(this, arguments);
30
- };
31
-
32
- function __rest(s, e) {
33
- var t = {};
34
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
35
- t[p] = s[p];
36
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
37
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
38
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
39
- t[p[i]] = s[p[i]];
40
- }
41
- return t;
42
- }
43
-
44
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
45
- var e = new Error(message);
46
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
11
+ var createContext = (pluginRoot, coreCtx) => {
12
+ coreCtx["sdk-react"] = {
13
+ rootDir: pluginRoot,
14
+ templatesDir: resolve(pluginRoot, "templates"),
15
+ outputOptions: {
16
+ fileName: "embeddable-prepared",
17
+ buildName: "embeddable-prepared-build",
18
+ componentsEntryPointFilename: "embeddable-entry-point.jsx",
19
+ },
20
+ };
47
21
  };
48
22
 
49
- var EmbeddableStateContext = React.createContext({});
50
- var useEmbeddableState = function (initialState) {
51
- if (initialState === void 0) { initialState = {}; }
52
- var ctx = React.useContext(EmbeddableStateContext);
53
- React.useEffect(function () {
54
- ctx[1](initialState);
55
- }, [initialState]);
56
- return ctx;
23
+ const oraP = import('ora');
24
+ const EMB_FILE_REGEX = /^(.*)(?<!\.type|\.options)\.emb\.[jt]s$/;
25
+ const EMB_TYPE_FILE_REGEX = /^(.*)\.type\.emb\.[jt]s$/;
26
+ var generate = async (ctx) => {
27
+ const ora = (await oraP).default;
28
+ const progress = ora("React: building components...").start();
29
+ const filesList = await findFiles(ctx.client.srcDir, EMB_FILE_REGEX);
30
+ await injectImports(ctx, filesList);
31
+ await runViteBuild(ctx);
32
+ progress.succeed("React: components built completed");
57
33
  };
34
+ async function runViteBuild(ctx) {
35
+ process.chdir(ctx.client.rootDir);
36
+ await vite.build({
37
+ logLevel: "error",
38
+ plugins: [
39
+ viteReactPlugin(),
40
+ extractComponentsConfigPlugin({
41
+ globalKey: "componentsMeta",
42
+ fileName: "embeddable-components-meta.js",
43
+ outputDir: ".embeddable-build",
44
+ componentFileRegex: EMB_FILE_REGEX,
45
+ typeFileRegex: EMB_TYPE_FILE_REGEX,
46
+ searchEntry: "embedComponent",
47
+ }),
48
+ extractComponentsConfigPlugin({
49
+ globalKey: "editorsMeta",
50
+ fileName: "embeddable-editors-meta.js",
51
+ outputDir: ".embeddable-build",
52
+ componentFileRegex: EMB_FILE_REGEX,
53
+ typeFileRegex: EMB_TYPE_FILE_REGEX,
54
+ searchEntry: "embedControl",
55
+ }),
56
+ ],
57
+ build: {
58
+ lib: {
59
+ entry: `./${ctx["sdk-react"].outputOptions.componentsEntryPointFilename}`,
60
+ formats: ["es"],
61
+ fileName: ctx["sdk-react"].outputOptions.fileName,
62
+ },
63
+ outDir: `.embeddable-build/${ctx["sdk-react"].outputOptions.buildName}`,
64
+ },
65
+ define: { "process.env.NODE_ENV": '"production"' },
66
+ });
67
+ }
68
+ const REPLACE_TOKEN = "{{LAZY_IMPORTS}}";
69
+ async function injectImports(ctx, filesList) {
70
+ const imports = filesList
71
+ .map(([fileName, filePath]) => `\t${fileName}: React.lazy(() => import('./${path.relative(ctx.client.rootDir, filePath)}'))`)
72
+ .join(",\n");
73
+ const content = await fs.readFile(path.resolve(ctx["sdk-react"].templatesDir, `${ctx["sdk-react"].outputOptions.componentsEntryPointFilename}.template`), "utf8");
74
+ await fs.writeFile(path.resolve(ctx.client.rootDir, ctx["sdk-react"].outputOptions.componentsEntryPointFilename), content.replace(REPLACE_TOKEN, imports));
75
+ }
58
76
 
59
- var UPDATE_PROPS_EVENT_NAME = "embeddable-event:update-props";
60
- var RELOAD_DATASET_EVENT_NAME = "embeddable-event:reload-dataset";
61
- var LOAD_DATA_RESULT_EVENT_NAME = "embeddable-event:load-data-result";
62
- var ReducerActionTypes = {
63
- loading: "loading",
64
- error: "error",
65
- data: "data",
66
- };
67
- var reducer = function (state, action) {
68
- var _a, _b, _c;
69
- switch (action.type) {
70
- case ReducerActionTypes.loading: {
71
- return __assign(__assign({}, state), (_a = {}, _a[action.inputName] = {
72
- data: state[action.inputName].data,
73
- isLoading: true,
74
- }, _a));
75
- }
76
- case ReducerActionTypes.data: {
77
- return __assign(__assign({}, state), (_b = {}, _b[action.inputName] = { isLoading: false, data: action.payload }, _b));
78
- }
79
- case ReducerActionTypes.error: {
80
- return __assign(__assign({}, state), (_c = {}, _c[action.inputName] = {
81
- isLoading: false,
82
- error: action.payload.message || action.payload,
83
- }, _c));
84
- }
85
- }
86
- return state;
87
- };
88
- var createInitialLoadersState = function (dataLoaders) {
89
- return Object.keys(dataLoaders).reduce(function (loaderState, loaderKey) {
90
- var _a;
91
- return (__assign(__assign({}, loaderState), (_a = {}, _a[loaderKey] = { isLoading: false }, _a)));
92
- }, {});
77
+ var build = async (ctx) => {
78
+ createContext(path$1.resolve(__dirname, ".."), ctx);
79
+ await generate(ctx);
93
80
  };
94
- function embedComponent(InnerComponent, config) {
95
- var _a;
96
- if (config === void 0) { config = {}; }
97
- function EmbeddableWrapper(_a) {
98
- var propsUpdateListener = _a.propsUpdateListener, props = __rest(_a, ["propsUpdateListener"]);
99
- var _b = React.useState(props), propsProxy = _b[0], setProps = _b[1];
100
- var embeddableState = React.useState();
101
- var componentId = props.componentId;
102
- var loadDataResultEventName = "".concat(LOAD_DATA_RESULT_EVENT_NAME, ":").concat(componentId);
103
- var propsUpdateEventHandler = function (_a) {
104
- var detail = _a.detail;
105
- return setProps(detail);
106
- };
107
- React.useEffect(function () {
108
- propsUpdateListener.addEventListener(UPDATE_PROPS_EVENT_NAME, propsUpdateEventHandler);
109
- return function () {
110
- return propsUpdateListener.removeEventListener(UPDATE_PROPS_EVENT_NAME, propsUpdateEventHandler);
111
- };
112
- }, []);
113
- var _c = React.useMemo(function () {
114
- var _a, _b;
115
- return Object.entries((_b = (_a = config === null || config === void 0 ? void 0 : config.props) === null || _a === void 0 ? void 0 : _a.call(config, propsProxy, embeddableState)) !== null && _b !== void 0 ? _b : {}).reduce(function (acc, _a) {
116
- var key = _a[0], value = _a[1];
117
- if (isLoadDataParams(value)) {
118
- acc.dataLoaders[key] = value;
119
- }
120
- else {
121
- acc.extendedProps[key] = value;
122
- }
123
- return acc;
124
- }, { extendedProps: {}, dataLoaders: {} });
125
- }, [propsProxy, config === null || config === void 0 ? void 0 : config.props, embeddableState[0]]), extendedProps = _c.extendedProps, dataLoaders = _c.dataLoaders;
126
- var _d = React.useReducer(reducer, dataLoaders, createInitialLoadersState), loadersState = _d[0], dispatch = _d[1];
127
- var handleDataLoaded = function (inputName, data) {
128
- return dispatch({ type: ReducerActionTypes.data, inputName: inputName, payload: data });
129
- };
130
- var handleError = function (inputName, error) {
131
- return dispatch({ type: ReducerActionTypes.error, inputName: inputName, payload: error });
132
- };
133
- var reloadDataset = function (inputName, params) {
134
- dispatch({ type: ReducerActionTypes.loading, inputName: inputName });
135
- var error = params.dataLoader(params.requestParams, componentId, inputName);
136
- if (error)
137
- handleError(inputName, error);
138
- };
139
- var handleLoadDataResult = function (ev) {
140
- if (ev.detail.isSuccess) {
141
- handleDataLoaded(ev.detail.propertyName, ev.detail.data);
142
- }
143
- else {
144
- handleError(ev.detail.propertyName, ev.detail.error);
145
- }
146
- };
147
- var variableChangedEventHandler = function (_a) {
148
- var detail = _a.detail;
149
- Object.entries(dataLoaders)
150
- .filter(function (_a) {
151
- _a[0]; var params = _a[1];
152
- return params.requestParams.from.datasetId === detail.datasetId;
153
- })
154
- .forEach(function (_a) {
155
- var inputName = _a[0], params = _a[1];
156
- return reloadDataset(inputName, params);
157
- });
158
- };
159
- React.useEffect(function () {
160
- Object.entries(dataLoaders).forEach(function (_a) {
161
- var inputName = _a[0], params = _a[1];
162
- return reloadDataset(inputName, params);
163
- });
164
- window.addEventListener(RELOAD_DATASET_EVENT_NAME, variableChangedEventHandler);
165
- window.addEventListener(loadDataResultEventName, handleLoadDataResult);
166
- return function () {
167
- window.removeEventListener(RELOAD_DATASET_EVENT_NAME, variableChangedEventHandler);
168
- window.removeEventListener(loadDataResultEventName, handleLoadDataResult);
169
- };
170
- }, [
171
- JSON.stringify(Object.values(dataLoaders).map(function (loader) { return loader.requestParams; })),
172
- ]);
173
- var createEvent = function (value, eventName) {
174
- return setValue(value, componentId, eventName);
175
- };
176
- var events = config === null || config === void 0 ? void 0 : config.events;
177
- var eventProps = {};
178
- if (events) {
179
- var _loop_1 = function (event_1) {
180
- if (events.hasOwnProperty(event_1)) {
181
- var eventFunction_1 = events[event_1];
182
- eventProps[event_1] = function (value) {
183
- return createEvent(eventFunction_1(value), event_1);
184
- };
185
- }
186
- };
187
- for (var event_1 in events) {
188
- _loop_1(event_1);
189
- }
190
- }
191
- return (React.createElement(EmbeddableStateContext.Provider, { value: embeddableState },
192
- React.createElement(InnerComponent, __assign({}, extendedProps, eventProps, loadersState))));
193
- }
194
- EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : "Component", ")");
195
- return EmbeddableWrapper;
196
- }
197
81
 
198
- function embedControl(InnerComponent, config) {
199
- var _a;
200
- function EmbeddableWrapper(props) {
201
- var _a, _b;
202
- var componentId = props.componentId, initialValue = props.initialValue;
203
- var _c = React.useState(initialValue), componentState = _c[0], setComponentState = _c[1];
204
- var setter = function (value) {
205
- setComponentState(value);
206
- setValue(value, componentId);
207
- };
208
- return (React.createElement(InnerComponent, __assign({}, config.inputs(componentState, setter), ((_b = (_a = config.mapProps) === null || _a === void 0 ? void 0 : _a.call(config, props)) !== null && _b !== void 0 ? _b : {}))));
209
- }
210
- EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : "Editor", ")");
211
- return EmbeddableWrapper;
212
- }
82
+ var cleanup = async (ctx) => await rm(resolve(ctx.client.rootDir, ctx["sdk-react"].outputOptions.componentsEntryPointFilename));
83
+
84
+ var index = (coreCtx) => {
85
+ return {
86
+ pluginName: "sdk-react",
87
+ validate: async () => { },
88
+ build,
89
+ cleanup,
90
+ };
91
+ };
213
92
 
214
- export { embedComponent, embedControl, useEmbeddableState };
93
+ export { index as default };
@@ -0,0 +1,2 @@
1
+ declare const _default: (ctx: any) => Promise<void>;
2
+ export default _default;
@@ -0,0 +1,2 @@
1
+ declare const _default: (ctx: any) => Promise<void>;
2
+ export default _default;
@@ -0,0 +1,2 @@
1
+ declare const _default: (pluginRoot: string, coreCtx: any) => void;
2
+ export default _default;
@@ -0,0 +1,2 @@
1
+ declare const _default: (ctx: any) => Promise<void>;
2
+ export default _default;
@@ -0,0 +1,7 @@
1
+ declare const _default: (coreCtx: any) => {
2
+ pluginName: string;
3
+ validate: () => Promise<void>;
4
+ build: (ctx: any) => Promise<void>;
5
+ cleanup: (ctx: any) => Promise<void>;
6
+ };
7
+ export default _default;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@embeddable.com/sdk-react",
3
- "version": "1.0.0",
4
- "description": "Embeddable SDK React plugin/module responsible for React components bundling.",
3
+ "version": "2.0.0",
4
+ "description": "Embeddable SDK React plugin responsible for React components bundling.",
5
5
  "keywords": [
6
6
  "embeddable",
7
7
  "sdk",
@@ -9,19 +9,15 @@
9
9
  ],
10
10
  "main": "lib/index.cjs.js",
11
11
  "module": "lib/index.esm.js",
12
- "browser": "lib/index.umd.js",
13
12
  "types": "lib/index.d.ts",
14
13
  "repository": {
15
14
  "type": "git",
16
15
  "url": "git+https://github.com/embeddable-hq/embeddable-sdk.git",
17
- "directory": "packages/react"
16
+ "directory": "packages/react-plugin"
18
17
  },
19
18
  "scripts": {
20
19
  "build": "rollup -c"
21
20
  },
22
- "bin": {
23
- "embeddable-react": "bin/embeddable-react"
24
- },
25
21
  "author": "Oleg Kapustin <oleg@trevor.io>",
26
22
  "files": [
27
23
  "lib/",
@@ -29,18 +25,11 @@
29
25
  "templates/"
30
26
  ],
31
27
  "license": "MIT",
32
- "peerDependencies": {
33
- "react": "^16.8.0 || ^17.0.0 || ^18.0.0"
34
- },
35
- "devDependencies": {
36
- "@types/react": "^18.2.14",
37
- "react": "^18.2.0"
38
- },
39
28
  "dependencies": {
29
+ "@embeddable.com/extract-components-config": "*",
40
30
  "@embeddable.com/sdk-core": "*",
41
- "@vitejs/plugin-react": "^4.0.2",
42
- "vite": "^4.4.2",
43
- "ora": "^6.3.1"
31
+ "@embeddable.com/sdk-utils": "*",
32
+ "@vitejs/plugin-react": "^4.0.2"
44
33
  },
45
34
  "lint-staged": {
46
35
  "*.{js,ts,jsx,tsx,json}": [
@@ -8,10 +8,16 @@ const COMPONENT_MAP = {
8
8
  };
9
9
 
10
10
  export default (rootEl, componentName, props) => {
11
- const Component = COMPONENT_MAP[componentName]
12
- ReactDOM.createRoot(rootEl).render(
11
+ const Component = COMPONENT_MAP[componentName];
12
+ const root = ReactDOM.createRoot(rootEl);
13
+ const unmountHandler = () => {
14
+ root.unmount();
15
+ rootEl.removeEventListener('EMBEDDABLE_COMPONENT:UNMOUNT', unmountHandler);
16
+ };
17
+ root.render(
13
18
  <React.Suspense fallback={<div/>}>
14
19
  <Component {...props} propsUpdateListener={rootEl} />
15
20
  </React.Suspense>
16
- )
21
+ );
22
+ rootEl.addEventListener('EMBEDDABLE_COMPONENT:UNMOUNT', unmountHandler);
17
23
  }
@@ -1,10 +0,0 @@
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();
@@ -1,3 +0,0 @@
1
- import * as React from "react";
2
- export declare const EmbeddableStateContext: React.Context<{}>;
3
- export declare const useEmbeddableState: <S>(initialState?: S) => {};
@@ -1,21 +0,0 @@
1
- import * as React from "react";
2
- import { LoadDataParams } from "@embeddable.com/sdk-core";
3
- type WrapperProps = {
4
- propsUpdateListener: HTMLElement;
5
- componentId: string;
6
- };
7
- export type Config<ES> = {
8
- props?: <P>(ownProps: P, embeddableState: [ES, React.Dispatch<React.SetStateAction<ES>>]) => Record<string, unknown | LoadDataParams>;
9
- events?: Record<string, EmbeddableEventHandler>;
10
- };
11
- export type EmbeddableEventHandler = (value: any) => any;
12
- export type DataResponse = {
13
- isLoading: boolean;
14
- data?: any;
15
- error?: string;
16
- };
17
- export declare function embedComponent<ES>(InnerComponent: React.ComponentType<any>, config?: Config<ES>): {
18
- ({ propsUpdateListener, ...props }: WrapperProps): React.JSX.Element;
19
- displayName: string;
20
- };
21
- export {};
@@ -1,13 +0,0 @@
1
- import * as React from "react";
2
- export type Config<T> = {
3
- inputs: (value: any, setter: Setter<T>) => any;
4
- events: Record<string, EmbeddableEventHandler<T>>;
5
- mapProps?: (_: any) => any;
6
- };
7
- export type EmbeddableEventHandler<T> = (value: T) => T;
8
- type Setter<T> = (value: T) => void;
9
- export declare function embedControl<T>(InnerComponent: React.ComponentType, config: Config<T>): {
10
- (props: any): React.JSX.Element;
11
- displayName: string;
12
- };
13
- export {};
package/lib/index.d.ts DELETED
@@ -1,3 +0,0 @@
1
- export { embedComponent } from "./embedComponent";
2
- export { embedControl } from "./embedControl";
3
- export { useEmbeddableState } from "./EmbeddableStateContext";
package/lib/index.umd.js DELETED
@@ -1,280 +0,0 @@
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 isLoadDataParams = function (ldp) {
90
- return typeof ldp === "object" && "requestParams" in ldp && "dataLoader" in ldp;
91
- };
92
-
93
- var UPDATE_VALUE_EVENT = "embeddable:value:changed";
94
- var setValue = function (value, componentId, eventName) {
95
- var event = new CustomEvent(UPDATE_VALUE_EVENT, {
96
- bubbles: false,
97
- detail: {
98
- componentId: componentId,
99
- value: value,
100
- eventName: eventName,
101
- },
102
- });
103
- window.dispatchEvent(event);
104
- };
105
-
106
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
107
- var e = new Error(message);
108
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
109
- };
110
-
111
- var EmbeddableStateContext = reactExports.createContext({});
112
- var useEmbeddableState = function (initialState) {
113
- if (initialState === void 0) { initialState = {}; }
114
- var ctx = reactExports.useContext(EmbeddableStateContext);
115
- reactExports.useEffect(function () {
116
- ctx[1](initialState);
117
- }, [initialState]);
118
- return ctx;
119
- };
120
-
121
- var UPDATE_PROPS_EVENT_NAME = "embeddable-event:update-props";
122
- var RELOAD_DATASET_EVENT_NAME = "embeddable-event:reload-dataset";
123
- var LOAD_DATA_RESULT_EVENT_NAME = "embeddable-event:load-data-result";
124
- var ReducerActionTypes = {
125
- loading: "loading",
126
- error: "error",
127
- data: "data",
128
- };
129
- var reducer = function (state, action) {
130
- var _a, _b, _c;
131
- switch (action.type) {
132
- case ReducerActionTypes.loading: {
133
- return __assign(__assign({}, state), (_a = {}, _a[action.inputName] = {
134
- data: state[action.inputName].data,
135
- isLoading: true,
136
- }, _a));
137
- }
138
- case ReducerActionTypes.data: {
139
- return __assign(__assign({}, state), (_b = {}, _b[action.inputName] = { isLoading: false, data: action.payload }, _b));
140
- }
141
- case ReducerActionTypes.error: {
142
- return __assign(__assign({}, state), (_c = {}, _c[action.inputName] = {
143
- isLoading: false,
144
- error: action.payload.message || action.payload,
145
- }, _c));
146
- }
147
- }
148
- return state;
149
- };
150
- var createInitialLoadersState = function (dataLoaders) {
151
- return Object.keys(dataLoaders).reduce(function (loaderState, loaderKey) {
152
- var _a;
153
- return (__assign(__assign({}, loaderState), (_a = {}, _a[loaderKey] = { isLoading: false }, _a)));
154
- }, {});
155
- };
156
- function embedComponent(InnerComponent, config) {
157
- var _a;
158
- if (config === void 0) { config = {}; }
159
- function EmbeddableWrapper(_a) {
160
- var propsUpdateListener = _a.propsUpdateListener, props = __rest(_a, ["propsUpdateListener"]);
161
- var _b = reactExports.useState(props), propsProxy = _b[0], setProps = _b[1];
162
- var embeddableState = reactExports.useState();
163
- var componentId = props.componentId;
164
- var loadDataResultEventName = "".concat(LOAD_DATA_RESULT_EVENT_NAME, ":").concat(componentId);
165
- var propsUpdateEventHandler = function (_a) {
166
- var detail = _a.detail;
167
- return setProps(detail);
168
- };
169
- reactExports.useEffect(function () {
170
- propsUpdateListener.addEventListener(UPDATE_PROPS_EVENT_NAME, propsUpdateEventHandler);
171
- return function () {
172
- return propsUpdateListener.removeEventListener(UPDATE_PROPS_EVENT_NAME, propsUpdateEventHandler);
173
- };
174
- }, []);
175
- var _c = reactExports.useMemo(function () {
176
- var _a, _b;
177
- return Object.entries((_b = (_a = config === null || config === void 0 ? void 0 : config.props) === null || _a === void 0 ? void 0 : _a.call(config, propsProxy, embeddableState)) !== null && _b !== void 0 ? _b : {}).reduce(function (acc, _a) {
178
- var key = _a[0], value = _a[1];
179
- if (isLoadDataParams(value)) {
180
- acc.dataLoaders[key] = value;
181
- }
182
- else {
183
- acc.extendedProps[key] = value;
184
- }
185
- return acc;
186
- }, { extendedProps: {}, dataLoaders: {} });
187
- }, [propsProxy, config === null || config === void 0 ? void 0 : config.props, embeddableState[0]]), extendedProps = _c.extendedProps, dataLoaders = _c.dataLoaders;
188
- var _d = reactExports.useReducer(reducer, dataLoaders, createInitialLoadersState), loadersState = _d[0], dispatch = _d[1];
189
- var handleDataLoaded = function (inputName, data) {
190
- return dispatch({ type: ReducerActionTypes.data, inputName: inputName, payload: data });
191
- };
192
- var handleError = function (inputName, error) {
193
- return dispatch({ type: ReducerActionTypes.error, inputName: inputName, payload: error });
194
- };
195
- var reloadDataset = function (inputName, params) {
196
- dispatch({ type: ReducerActionTypes.loading, inputName: inputName });
197
- var error = params.dataLoader(params.requestParams, componentId, inputName);
198
- if (error)
199
- handleError(inputName, error);
200
- };
201
- var handleLoadDataResult = function (ev) {
202
- if (ev.detail.isSuccess) {
203
- handleDataLoaded(ev.detail.propertyName, ev.detail.data);
204
- }
205
- else {
206
- handleError(ev.detail.propertyName, ev.detail.error);
207
- }
208
- };
209
- var variableChangedEventHandler = function (_a) {
210
- var detail = _a.detail;
211
- Object.entries(dataLoaders)
212
- .filter(function (_a) {
213
- _a[0]; var params = _a[1];
214
- return params.requestParams.from.datasetId === detail.datasetId;
215
- })
216
- .forEach(function (_a) {
217
- var inputName = _a[0], params = _a[1];
218
- return reloadDataset(inputName, params);
219
- });
220
- };
221
- reactExports.useEffect(function () {
222
- Object.entries(dataLoaders).forEach(function (_a) {
223
- var inputName = _a[0], params = _a[1];
224
- return reloadDataset(inputName, params);
225
- });
226
- window.addEventListener(RELOAD_DATASET_EVENT_NAME, variableChangedEventHandler);
227
- window.addEventListener(loadDataResultEventName, handleLoadDataResult);
228
- return function () {
229
- window.removeEventListener(RELOAD_DATASET_EVENT_NAME, variableChangedEventHandler);
230
- window.removeEventListener(loadDataResultEventName, handleLoadDataResult);
231
- };
232
- }, [
233
- JSON.stringify(Object.values(dataLoaders).map(function (loader) { return loader.requestParams; })),
234
- ]);
235
- var createEvent = function (value, eventName) {
236
- return setValue(value, componentId, eventName);
237
- };
238
- var events = config === null || config === void 0 ? void 0 : config.events;
239
- var eventProps = {};
240
- if (events) {
241
- var _loop_1 = function (event_1) {
242
- if (events.hasOwnProperty(event_1)) {
243
- var eventFunction_1 = events[event_1];
244
- eventProps[event_1] = function (value) {
245
- return createEvent(eventFunction_1(value), event_1);
246
- };
247
- }
248
- };
249
- for (var event_1 in events) {
250
- _loop_1(event_1);
251
- }
252
- }
253
- return (reactExports.createElement(EmbeddableStateContext.Provider, { value: embeddableState },
254
- reactExports.createElement(InnerComponent, __assign({}, extendedProps, eventProps, loadersState))));
255
- }
256
- EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : "Component", ")");
257
- return EmbeddableWrapper;
258
- }
259
-
260
- function embedControl(InnerComponent, config) {
261
- var _a;
262
- function EmbeddableWrapper(props) {
263
- var _a, _b;
264
- var componentId = props.componentId, initialValue = props.initialValue;
265
- var _c = reactExports.useState(initialValue), componentState = _c[0], setComponentState = _c[1];
266
- var setter = function (value) {
267
- setComponentState(value);
268
- setValue(value, componentId);
269
- };
270
- return (reactExports.createElement(InnerComponent, __assign({}, config.inputs(componentState, setter), ((_b = (_a = config.mapProps) === null || _a === void 0 ? void 0 : _a.call(config, props)) !== null && _b !== void 0 ? _b : {}))));
271
- }
272
- EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : "Editor", ")");
273
- return EmbeddableWrapper;
274
- }
275
-
276
- exports.embedComponent = embedComponent;
277
- exports.embedControl = embedControl;
278
- exports.useEmbeddableState = useEmbeddableState;
279
-
280
- }));
package/scripts/build.js DELETED
@@ -1,79 +0,0 @@
1
- const path = require("path");
2
- const { fork } = require("child_process");
3
- const oraP = import("ora");
4
- const core = require("@embeddable.com/sdk-core/scripts");
5
-
6
- const { createContext } = require("./createContext");
7
- const { prepare } = require("./prepare");
8
-
9
- let ora;
10
-
11
- async function build() {
12
- ora = (await oraP).default;
13
-
14
- const spinnerPrepare = ora("preparing...").start();
15
-
16
- const ctx = createContext(path.resolve(__dirname, ".."), process.cwd());
17
-
18
- await core.validate(ctx);
19
-
20
- await prepare(ctx);
21
- spinnerPrepare.succeed("preparation competed");
22
-
23
- await runProcess({
24
- ctx,
25
- processFile: "generateProcess.js",
26
- initMessage: "building components...",
27
- successMessage: "components built completed",
28
- failMessage: "components built failed",
29
- });
30
-
31
- await runProcess({
32
- ctx,
33
- processFile: "buildTypesProcess.js",
34
- initMessage: "building types...",
35
- successMessage: "types built completed",
36
- failMessage: "types built failed",
37
- });
38
- }
39
-
40
-
41
- module.exports = { build };
42
-
43
- async function runProcess({ processFile, ctx, initMessage, successMessage, failMessage }) {
44
- const spinner = ora(initMessage).start();
45
- try {
46
- await promisifyForkedProcess(processFile, ctx);
47
- spinner.succeed(successMessage);
48
- } catch ({ watchFiles, ...info }) {
49
- spinner.fail(failMessage);
50
- console.log(info);
51
- await core.globalCleanup(ctx);
52
- process.exit(1);
53
- }
54
- }
55
-
56
- function promisifyForkedProcess (fileName, ctx) {
57
- const forkedProcess = fork(
58
- path.resolve(__dirname, fileName),
59
- [],
60
- process.env.NODE_ENV === "dev" ? undefined : { silent: true },
61
- );
62
-
63
- forkedProcess.send({ ctx });
64
-
65
- return new Promise((resolve, reject) => {
66
- forkedProcess.on("exit", (code) => {
67
- if (code === 0) resolve();
68
- });
69
-
70
- forkedProcess.on("message", ({ error }) => {
71
- if (!error) return;
72
-
73
- reject(error);
74
- })
75
- });
76
- }
77
-
78
-
79
-
@@ -1,12 +0,0 @@
1
- const core = require("@embeddable.com/sdk-core/scripts");
2
-
3
- process.on("message", async ({ ctx }) => {
4
- try {
5
- await core.buildTypes(ctx);
6
- } catch (error) {
7
- process.send({ error });
8
- process.exit(1);
9
- }
10
-
11
- process.exit();
12
- });
@@ -1,8 +0,0 @@
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, ctx.outputOptions.componentsEntryPointFilename));
6
- }
7
-
8
- module.exports = { cleanup };
@@ -1,24 +0,0 @@
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: {
15
- // TODO: should be specified via command parameters or from rc file.
16
- fileName: "embeddable-prepared",
17
- buildName: "embeddable-prepared-build",
18
- componentsEntryPointFilename: "embeddable-entry-point.jsx",
19
- typesEntryPointFilename: "embeddable-types-entry-point.js",
20
- },
21
- };
22
- }
23
-
24
- module.exports = { createContext };
@@ -1,70 +0,0 @@
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.com/sdk-core/scripts");
6
-
7
- const EMB_FILE_REGEX = /^(.*)(?<!\.type|\.options)\.emb\.[jt]s$/;
8
-
9
- async function generate(ctx) {
10
- const filesList = await core.findEmbFiles(ctx.client.srcDir, EMB_FILE_REGEX);
11
-
12
- await injectImports(ctx, filesList);
13
-
14
- await runViteBuild(ctx);
15
-
16
- await runCoreBuild(ctx);
17
- }
18
-
19
- module.exports = { generate };
20
-
21
- async function runCoreBuild(ctx) {
22
- await core.build({
23
- outDir: ctx.outputOptions.buildName,
24
- renderFunctionFileName: ctx.outputOptions.fileName,
25
- });
26
- }
27
-
28
- async function runViteBuild(ctx) {
29
- process.chdir(ctx.client.rootDir);
30
-
31
- await vite.build({
32
- plugins: [viteReactPlugin()],
33
- build: {
34
- lib: {
35
- entry: `./${ctx.outputOptions.componentsEntryPointFilename}`,
36
- formats: ["es"],
37
- fileName: ctx.outputOptions.fileName,
38
- },
39
- outDir: `.embeddable-build/${ctx.outputOptions.buildName}`,
40
- },
41
- define: { "process.env.NODE_ENV": '"production"' },
42
- });
43
- }
44
-
45
- const REPLACE_TOKEN = "{{LAZY_IMPORTS}}";
46
-
47
- async function injectImports(ctx, filesList) {
48
- const imports = filesList
49
- .map(
50
- ([fileName, filePath]) =>
51
- `\t${fileName}: React.lazy(() => import('./${path.relative(
52
- ctx.client.rootDir,
53
- filePath,
54
- )}'))`,
55
- )
56
- .join(",\n");
57
-
58
- const content = await fs.readFile(
59
- path.resolve(
60
- ctx.plugin.templatesDir,
61
- `${ctx.outputOptions.componentsEntryPointFilename}.template`,
62
- ),
63
- "utf8",
64
- );
65
-
66
- await fs.writeFile(
67
- path.resolve(ctx.client.rootDir, ctx.outputOptions.componentsEntryPointFilename),
68
- content.replace(REPLACE_TOKEN, imports),
69
- );
70
- }
@@ -1,14 +0,0 @@
1
- const { generate } = require("./generate");
2
- const { cleanup } = require("./cleanup");
3
-
4
- process.on("message", async ({ ctx }) => {
5
- try {
6
- await generate(ctx);
7
- await cleanup(ctx);
8
- } catch (error) {
9
- process.send({ error });
10
- process.exit(1);
11
- }
12
-
13
- process.exit();
14
- });
@@ -1,12 +0,0 @@
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
- }