@embeddable.com/sdk-react 1.0.0 → 2.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.
package/lib/index.esm.js CHANGED
@@ -1,214 +1,166 @@
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, join } from 'node:path';
3
+ import * as fs$1 from 'fs/promises';
4
+ import * as path from 'path';
5
+ import * as vite from 'vite';
6
+ import viteReactPlugin from '@vitejs/plugin-react';
7
+ import * as fs from 'node:fs/promises';
8
+ import { readdir, lstat, rm } from 'node:fs/promises';
9
+ import { parse } from '@babel/parser';
10
+ import generator from '@babel/generator';
11
+ import traverse from '@babel/traverse';
12
+ import 'node:child_process';
3
13
 
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;
14
+ var createContext = (pluginRoot, coreCtx) => {
15
+ coreCtx["sdk-react"] = {
16
+ rootDir: pluginRoot,
17
+ templatesDir: resolve(pluginRoot, "templates"),
18
+ outputOptions: {
19
+ fileName: "embeddable-prepared",
20
+ buildName: "embeddable-prepared-build",
21
+ componentsEntryPointFilename: "embeddable-entry-point.jsx",
22
+ },
23
+ };
47
24
  };
48
25
 
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;
26
+ // @ts-ignore
27
+ const babelTraverse = traverse.default;
28
+ // @ts-ignore
29
+ const babelGenerate = generator.default;
30
+ var index$1 = ({ globalKey, outputDir, fileName, componentFileRegex, typeFileRegex, searchEntry = "", }) => {
31
+ const configs = [];
32
+ return {
33
+ name: "extract-components-config",
34
+ moduleParsed: async (moduleInfo) => {
35
+ var _a;
36
+ if (componentFileRegex.test(moduleInfo.id) &&
37
+ ((_a = moduleInfo.code) === null || _a === void 0 ? void 0 : _a.includes(searchEntry))) {
38
+ const ast = parse(moduleInfo.code, {
39
+ sourceType: "module",
40
+ });
41
+ babelTraverse(ast, {
42
+ ImportDeclaration: (path) => {
43
+ if (!typeFileRegex.test(path.node.source.value)) {
44
+ path.remove();
45
+ }
46
+ },
47
+ ExportDefaultDeclaration: (path) => {
48
+ path.remove();
49
+ },
50
+ });
51
+ const tempFilePath = moduleInfo.id
52
+ .replace(".emb.", ".emb-temp.")
53
+ .replace(/\.ts$/, ".js");
54
+ await fs.writeFile(tempFilePath, babelGenerate(ast).code);
55
+ const module = await import(tempFilePath);
56
+ const configJSON = JSON.stringify(module.meta, (_key, value) => typeof value === "object" && "typeConfig" in value
57
+ ? value.toString()
58
+ : value);
59
+ await fs.rm(tempFilePath);
60
+ configs.push(configJSON);
61
+ }
62
+ },
63
+ buildEnd: async () => {
64
+ const template = `
65
+ globalThis.__EMBEDDABLE__ = globalThis.__EMBEDDABLE__ || {};
66
+ globalThis.__EMBEDDABLE__.${globalKey} = globalThis.__EMBEDDABLE__.${globalKey} || [
67
+ __PLACEHOLDER__
68
+ ];
69
+ `;
70
+ await fs.writeFile(`${outputDir}/${fileName}`, template.replace("__PLACEHOLDER__", configs.filter(Boolean).join(",\n")));
71
+ },
72
+ };
57
73
  };
58
74
 
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
- }, {});
93
- };
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);
75
+ var findFiles = async (initialSrcDir, regex) => {
76
+ const filesList = [];
77
+ async function findFilesRec(srcDir) {
78
+ const allFiles = await readdir(srcDir);
79
+ for (const file of allFiles) {
80
+ const filePath = join(srcDir, file);
81
+ const status = await lstat(filePath);
82
+ if (status.isDirectory()) {
83
+ await findFilesRec(filePath);
142
84
  }
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);
85
+ const fileName = file.match(regex);
86
+ if (fileName) {
87
+ filesList.push([fileName[1], filePath]);
189
88
  }
190
89
  }
191
- return (React.createElement(EmbeddableStateContext.Provider, { value: embeddableState },
192
- React.createElement(InnerComponent, __assign({}, extendedProps, eventProps, loadersState))));
193
90
  }
194
- EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : "Component", ")");
195
- return EmbeddableWrapper;
196
- }
91
+ await findFilesRec(initialSrcDir);
92
+ return filesList;
93
+ };
197
94
 
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;
95
+ const oraP = import('ora');
96
+ const EMB_FILE_REGEX = /^(.*)(?<!\.type|\.options)\.emb\.[jt]s$/;
97
+ const EMB_TYPE_FILE_REGEX = /^(.*)\.type\.emb\.[jt]s$/;
98
+ var generate = async (ctx) => {
99
+ const ora = (await oraP).default;
100
+ const progress = ora("React: building components...").start();
101
+ const filesList = await findFiles(ctx.client.srcDir, EMB_FILE_REGEX);
102
+ await injectImports(ctx, filesList);
103
+ await runViteBuild(ctx);
104
+ progress.succeed("React: components built completed");
105
+ };
106
+ async function runViteBuild(ctx) {
107
+ process.chdir(ctx.client.rootDir);
108
+ await vite.build({
109
+ logLevel: "error",
110
+ plugins: [
111
+ viteReactPlugin(),
112
+ index$1({
113
+ globalKey: "componentsMeta",
114
+ fileName: "embeddable-components-meta.js",
115
+ outputDir: ".embeddable-build",
116
+ componentFileRegex: EMB_FILE_REGEX,
117
+ typeFileRegex: EMB_TYPE_FILE_REGEX,
118
+ searchEntry: "embedComponent",
119
+ }),
120
+ index$1({
121
+ globalKey: "editorsMeta",
122
+ fileName: "embeddable-editors-meta.js",
123
+ outputDir: ".embeddable-build",
124
+ componentFileRegex: EMB_FILE_REGEX,
125
+ typeFileRegex: EMB_TYPE_FILE_REGEX,
126
+ searchEntry: "embedControl",
127
+ }),
128
+ ],
129
+ build: {
130
+ lib: {
131
+ entry: `./${ctx["sdk-react"].outputOptions.componentsEntryPointFilename}`,
132
+ formats: ["es"],
133
+ fileName: ctx["sdk-react"].outputOptions.fileName,
134
+ },
135
+ outDir: `.embeddable-build/${ctx["sdk-react"].outputOptions.buildName}`,
136
+ },
137
+ define: { "process.env.NODE_ENV": '"production"' },
138
+ });
212
139
  }
140
+ const REPLACE_TOKEN = "{{LAZY_IMPORTS}}";
141
+ async function injectImports(ctx, filesList) {
142
+ const imports = filesList
143
+ .map(([fileName, filePath]) => `\t${fileName}: React.lazy(() => import('./${path.relative(ctx.client.rootDir, filePath)}'))`)
144
+ .join(",\n");
145
+ const content = await fs$1.readFile(path.resolve(ctx["sdk-react"].templatesDir, `${ctx["sdk-react"].outputOptions.componentsEntryPointFilename}.template`), "utf8");
146
+ await fs$1.writeFile(path.resolve(ctx.client.rootDir, ctx["sdk-react"].outputOptions.componentsEntryPointFilename), content.replace(REPLACE_TOKEN, imports));
147
+ }
148
+
149
+ var build = async (ctx) => {
150
+ createContext(path$1.resolve(__dirname, ".."), ctx);
151
+ await generate(ctx);
152
+ };
153
+
154
+ var cleanup = async (ctx) => await rm(resolve(ctx.client.rootDir, ctx["sdk-react"].outputOptions.componentsEntryPointFilename));
155
+
156
+ var index = (coreCtx) => {
157
+ return {
158
+ pluginName: "sdk-react",
159
+ validate: async () => { },
160
+ build,
161
+ cleanup,
162
+ };
163
+ };
213
164
 
214
- export { embedComponent, embedControl, useEmbeddableState };
165
+ export { index as default };
166
+ //# sourceMappingURL=index.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.esm.js","sources":["../../src/createContext.ts","../../extract-components-config/lib/index.esm.js","../../utils/lib/index.esm.js","../../src/generate.ts","../../src/build.ts","../../src/cleanup.ts","../../src/index.ts"],"sourcesContent":[null,"import * as fs from 'node:fs/promises';\nimport { parse } from '@babel/parser';\nimport generator from '@babel/generator';\nimport traverse from '@babel/traverse';\n\n// @ts-ignore\nconst babelTraverse = traverse.default;\n// @ts-ignore\nconst babelGenerate = generator.default;\nvar index = ({ globalKey, outputDir, fileName, componentFileRegex, typeFileRegex, searchEntry = \"\", }) => {\n const configs = [];\n return {\n name: \"extract-components-config\",\n moduleParsed: async (moduleInfo) => {\n var _a;\n if (componentFileRegex.test(moduleInfo.id) &&\n ((_a = moduleInfo.code) === null || _a === void 0 ? void 0 : _a.includes(searchEntry))) {\n const ast = parse(moduleInfo.code, {\n sourceType: \"module\",\n });\n babelTraverse(ast, {\n ImportDeclaration: (path) => {\n if (!typeFileRegex.test(path.node.source.value)) {\n path.remove();\n }\n },\n ExportDefaultDeclaration: (path) => {\n path.remove();\n },\n });\n const tempFilePath = moduleInfo.id\n .replace(\".emb.\", \".emb-temp.\")\n .replace(/\\.ts$/, \".js\");\n await fs.writeFile(tempFilePath, babelGenerate(ast).code);\n const module = await import(tempFilePath);\n const configJSON = JSON.stringify(module.meta, (_key, value) => typeof value === \"object\" && \"typeConfig\" in value\n ? value.toString()\n : value);\n await fs.rm(tempFilePath);\n configs.push(configJSON);\n }\n },\n buildEnd: async () => {\n const template = `\nglobalThis.__EMBEDDABLE__ = globalThis.__EMBEDDABLE__ || {};\nglobalThis.__EMBEDDABLE__.${globalKey} = globalThis.__EMBEDDABLE__.${globalKey} || [\n __PLACEHOLDER__\n];\n `;\n await fs.writeFile(`${outputDir}/${fileName}`, template.replace(\"__PLACEHOLDER__\", configs.filter(Boolean).join(\",\\n\")));\n },\n };\n};\n\nexport { index as default };\n//# sourceMappingURL=index.esm.js.map\n","import { readdir, lstat } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { fork } from 'node:child_process';\n\nvar findFiles = async (initialSrcDir, regex) => {\n const filesList = [];\n async function findFilesRec(srcDir) {\n const allFiles = await readdir(srcDir);\n for (const file of allFiles) {\n const filePath = join(srcDir, file);\n const status = await lstat(filePath);\n if (status.isDirectory()) {\n await findFilesRec(filePath);\n }\n const fileName = file.match(regex);\n if (fileName) {\n filesList.push([fileName[1], filePath]);\n }\n }\n }\n await findFilesRec(initialSrcDir);\n return filesList;\n};\n\nvar runProcess = async ({ processFile, ctx, initMessage, successMessage, failMessage, }) => {\n const ora = (await import('ora')).default;\n const spinner = ora(initMessage).start();\n try {\n await promisifyForkedProcess(processFile, ctx);\n spinner.succeed(successMessage);\n }\n catch (error) {\n spinner.fail(failMessage);\n console.error(error);\n // await core.globalCleanup(ctx);\n process.exit(1);\n }\n};\nfunction promisifyForkedProcess(filePath, ctx) {\n const forkedProcess = fork(filePath, [], process.env.NODE_ENV === \"dev\" ? undefined : { silent: true });\n forkedProcess.send({ ctx });\n return new Promise((resolve, reject) => {\n forkedProcess.on(\"exit\", (code) => {\n if (code === 0)\n resolve();\n });\n // @ts-ignore\n forkedProcess.on(\"message\", ({ error }) => {\n if (!error)\n return;\n reject(error);\n });\n });\n}\n\nexport { findFiles, runProcess };\n//# sourceMappingURL=index.esm.js.map\n",null,null,null,null],"names":["index","extractComponentsConfigPlugin","f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Aa,CAACC,MAAI,CAAC,OAAO,CAAC,SAAS,EAAE,IAAI,CAAC,EAAE,GAAG,CAAC,CAAC;AAElD,IAAA,MAAM,QAAQ,CAAC,GAAG,CAAC,CAAC;AACtB,CAAC;;ACPD,cAAe,OAAO,GAAQ,KAC5B,MAAM,EAAE,CACN,OAAO,CACL,GAAG,CAAC,MAAM,CAAC,OAAO,EAClB,GAAG,CAAC,WAAW,CAAC,CAAC,aAAa,CAAC,4BAA4B,CAC5D,CACF;;ACLH,YAAe,CAAC,OAAY,KAAI;IAC9B,OAAO;AACL,QAAA,UAAU,EAAE,WAAW;AACvB,QAAA,QAAQ,EAAE,eAAc;QACxB,KAAK;QACL,OAAO;KACR,CAAC;AACJ,CAAC;;;;"}
@@ -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.1",
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-sdk"
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,13 @@
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": "*",
31
+ "@embeddable.com/sdk-utils": "*",
41
32
  "@vitejs/plugin-react": "^4.0.2",
42
- "vite": "^4.4.2",
43
- "ora": "^6.3.1"
33
+ "ora": "^7.0.1",
34
+ "vite": "^4.5.0"
44
35
  },
45
36
  "lint-staged": {
46
37
  "*.{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";