@encatch/ws-react 0.2.1-beta.9 → 0.2.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/dist/index.es.js CHANGED
@@ -1,568 +1,261 @@
1
- import G, { useRef as L, useEffect as T, useCallback as z } from "react";
2
- var W = { exports: {} }, j = {};
3
- /**
4
- * @license React
5
- * react-jsx-runtime.production.js
6
- *
7
- * Copyright (c) Meta Platforms, Inc. and affiliates.
8
- *
9
- * This source code is licensed under the MIT license found in the
10
- * LICENSE file in the root directory of this source tree.
11
- */
12
- var K;
13
- function ae() {
14
- if (K) return j;
15
- K = 1;
16
- var u = Symbol.for("react.transitional.element"), r = Symbol.for("react.fragment");
17
- function n(a, s, f) {
18
- var m = null;
19
- if (f !== void 0 && (m = "" + f), s.key !== void 0 && (m = "" + s.key), "key" in s) {
20
- f = {};
21
- for (var w in s)
22
- w !== "key" && (f[w] = s[w]);
23
- } else f = s;
24
- return s = f.ref, {
25
- $$typeof: u,
26
- type: a,
27
- key: m,
28
- ref: s !== void 0 ? s : null,
29
- props: f
30
- };
31
- }
32
- return j.Fragment = r, j.jsx = n, j.jsxs = n, j;
1
+ import e, { useCallback as t, useEffect as n, useRef as r } from "react";
2
+ import { jsx as i } from "react/jsx-runtime";
3
+ //#region src/EncatchPreview.tsx
4
+ var a = ({ formConfig: a, formPageUrl: o, formId: s, scale: c = 100, instanceId: l, onFormEvent: u, prefillResponses: d }) => {
5
+ let f = !!(a && o), p = s ?? a?.formId ?? l ?? "preview", m = e.useRef(null), h = e.useRef(null), g = r(!1), _ = r(() => {}), v = r(d);
6
+ n(() => {
7
+ v.current = d;
8
+ }, [d]);
9
+ let y = r({});
10
+ n(() => {
11
+ u && u({
12
+ onSubmit: (e) => {
13
+ y.current.onSubmit = e;
14
+ },
15
+ onShow: (e) => {
16
+ y.current.onShow = e;
17
+ },
18
+ onClose: (e) => {
19
+ y.current.onClose = e;
20
+ },
21
+ onSectionChange: (e) => {
22
+ y.current.onSectionChange = e;
23
+ },
24
+ onQuestionAnswered: (e) => {
25
+ y.current.onQuestionAnswered = e;
26
+ },
27
+ onError: (e) => {
28
+ y.current.onError = e;
29
+ },
30
+ onRemindMeLater: (e) => {
31
+ y.current.onRemindMeLater = e;
32
+ }
33
+ });
34
+ }, [u]);
35
+ let b = t(() => {
36
+ if (!h.current?.contentWindow || !a) return;
37
+ let e = {
38
+ formId: p,
39
+ scale: c,
40
+ ...a
41
+ };
42
+ h.current.contentWindow.postMessage({
43
+ type: "sdk:formConfig",
44
+ data: e
45
+ }, "*");
46
+ }, [
47
+ a,
48
+ p,
49
+ c
50
+ ]);
51
+ _.current = b;
52
+ let x = t((e) => {
53
+ !h.current?.contentWindow || !Object.keys(e).length || h.current.contentWindow.postMessage({
54
+ type: "sdk:prefillResponses",
55
+ data: { responses: e }
56
+ }, "*");
57
+ }, []);
58
+ n(() => {
59
+ !f || !g.current || _.current();
60
+ }, [
61
+ f,
62
+ a,
63
+ b
64
+ ]), n(() => {
65
+ !d || !g.current || x(d);
66
+ }, [d, x]);
67
+ let S = t((e) => {
68
+ e.style.border = "none", e.style.width = "100%", e.style.height = "100%";
69
+ }, []);
70
+ return n(() => {
71
+ if (!f || !m.current || !a || !o) return;
72
+ let e = document.createElement("div");
73
+ e.className = "encatch-preview-inner", e.style.width = "100%", e.style.height = "100%", e.style.display = "flex", e.style.flexDirection = "column", e.style.justifyContent = "flex-end", e.style.overflow = "auto";
74
+ let t = document.createElement("iframe"), n = new URL(o, window.location.origin), r = a?.isFullScreen ? "shareable" : "in-app", i = new URL(`${n.pathname}/${r}`, n.origin);
75
+ i.searchParams.set("formId", p), i.searchParams.set("_t", String(Date.now())), t.src = i.toString(), t.title = "Encatch form", t.setAttribute("allow", "microphone *; camera *"), S(t), h.current = t, e.appendChild(t), m.current.appendChild(e);
76
+ let s = (e) => {
77
+ let t = e.data;
78
+ if (!t || typeof t != "object" || !t.type) return;
79
+ let n = t.type, r = t.formId, i = t.data;
80
+ switch (n.startsWith("encatch:") && (n = n.replace("encatch:", ""), r = t.payload?.feedbackConfigurationId, i = t.payload), n) {
81
+ case "form:resize":
82
+ h.current && i && typeof i.height == "number" && (h.current.style.height = `${i.height}px`);
83
+ break;
84
+ case "form:fullscreen":
85
+ h.current && i?.active && (h.current.style.height = "100%");
86
+ break;
87
+ case "form:ready":
88
+ g.current = !0, _.current(), v.current && Object.keys(v.current).length && x(v.current);
89
+ break;
90
+ case "form:close":
91
+ y.current.onClose?.({ timestamp: Date.now() });
92
+ break;
93
+ case "form:complete":
94
+ y.current.onClose?.({ timestamp: Date.now() });
95
+ break;
96
+ case "form:submit":
97
+ i && y.current.onSubmit && y.current.onSubmit({
98
+ feedbackConfigurationId: i.feedbackConfigurationId,
99
+ feedbackIdentifier: i.feedbackIdentifier,
100
+ response: i.response,
101
+ isPartialSubmit: i.isPartialSubmit,
102
+ timestamp: Date.now()
103
+ });
104
+ break;
105
+ case "form:show":
106
+ i && y.current.onShow && y.current.onShow({
107
+ feedbackConfigurationId: i.feedbackConfigurationId,
108
+ feedbackIdentifier: i.feedbackIdentifier,
109
+ timestamp: Date.now()
110
+ });
111
+ break;
112
+ case "form:started":
113
+ i && y.current.onShow && y.current.onShow({
114
+ feedbackConfigurationId: i.feedbackConfigurationId,
115
+ feedbackIdentifier: i.feedbackIdentifier,
116
+ timestamp: Date.now()
117
+ });
118
+ break;
119
+ case "form:section:change":
120
+ i && y.current.onSectionChange && y.current.onSectionChange({
121
+ feedbackConfigurationId: i.feedbackConfigurationId ?? r ?? "",
122
+ sectionIndex: i.sectionIndex,
123
+ sectionId: i.sectionId,
124
+ timestamp: Date.now()
125
+ });
126
+ break;
127
+ case "form:answered":
128
+ i && y.current.onQuestionAnswered && y.current.onQuestionAnswered({
129
+ feedbackConfigurationId: i.feedbackConfigurationId ?? r ?? "",
130
+ questionId: i.questionId,
131
+ questionType: i.questionType,
132
+ answer: i.answer,
133
+ timestamp: Date.now()
134
+ });
135
+ break;
136
+ case "form:error":
137
+ i && y.current.onError && y.current.onError({
138
+ feedbackConfigurationId: i.feedbackConfigurationId ?? r ?? "",
139
+ questionId: i.questionId,
140
+ error: i.error ?? "Unknown error",
141
+ timestamp: Date.now()
142
+ });
143
+ break;
144
+ case "form:remindmelater":
145
+ y.current.onRemindMeLater?.({
146
+ feedbackConfigurationId: i?.feedbackConfigurationId ?? r ?? "",
147
+ feedbackIdentifier: i?.feedbackIdentifier,
148
+ timestamp: Date.now()
149
+ });
150
+ break;
151
+ default: break;
152
+ }
153
+ };
154
+ return window.addEventListener("message", s), () => {
155
+ window.removeEventListener("message", s), g.current = !1, e.parentNode && e.parentNode.removeChild(e), h.current = null;
156
+ };
157
+ }, [
158
+ f,
159
+ o,
160
+ p
161
+ ]), /* @__PURE__ */ i("div", {
162
+ ref: m,
163
+ title: "encatchPreview1",
164
+ style: f ? {
165
+ width: "100%",
166
+ height: "100%"
167
+ } : void 0
168
+ });
169
+ }, o = new class extends EventTarget {
170
+ subscriptions = /* @__PURE__ */ new Map();
171
+ targetOrigin = "*";
172
+ matchesFilter(e, t) {
173
+ return !t || t === "*" || t == null ? !0 : typeof t == "string" ? e === t : Array.isArray(t) ? t.includes(e || "") : typeof t == "function" ? t(e || "") : !1;
174
+ }
175
+ getFormIdFromPayload(e) {
176
+ return e?.feedbackConfigurationId;
177
+ }
178
+ publish(e, t, n) {
179
+ typeof window < "u" && window.dispatchEvent(new CustomEvent(e, {
180
+ detail: t,
181
+ bubbles: !0
182
+ })), n?.usePostMessage !== !1 && this.sendPostMessage(e, t);
183
+ }
184
+ subscribe(e, t, n) {
185
+ let r = Symbol("subscription"), i = {
186
+ eventType: e,
187
+ handler: t,
188
+ filter: n?.formId,
189
+ id: r,
190
+ once: n?.once
191
+ };
192
+ this.subscriptions.has(e) || this.subscriptions.set(e, []), this.subscriptions.get(e).push(i);
193
+ let a = (r) => {
194
+ let i = r, o = this.getFormIdFromPayload(i.detail);
195
+ this.matchesFilter(o, n?.formId) && (t(i.detail), n?.once && typeof window < "u" && window.removeEventListener(e, a));
196
+ };
197
+ return typeof window < "u" && window.addEventListener(e, a), () => {
198
+ this.unsubscribe(r), typeof window < "u" && window.removeEventListener(e, a);
199
+ };
200
+ }
201
+ unsubscribe(e) {
202
+ for (let [t, n] of this.subscriptions.entries()) {
203
+ let r = n.findIndex((t) => t.id === e);
204
+ if (r !== -1) {
205
+ n.splice(r, 1), n.length === 0 && this.subscriptions.delete(t);
206
+ break;
207
+ }
208
+ }
209
+ }
210
+ subscribeAll(e, t) {
211
+ let n = [
212
+ "form:show",
213
+ "form:started",
214
+ "form:submit",
215
+ "form:close",
216
+ "form:section:change",
217
+ "form:answered",
218
+ "form:error",
219
+ "form:remindmelater"
220
+ ], r = [];
221
+ return n.forEach((n) => {
222
+ let i = this.subscribe(n, (t) => e(n, t), t);
223
+ r.push(i);
224
+ }), () => {
225
+ r.forEach((e) => e());
226
+ };
227
+ }
228
+ getSubscriptionCount(e) {
229
+ return e ? this.subscriptions.get(e)?.length || 0 : Array.from(this.subscriptions.values()).reduce((e, t) => e + t.length, 0);
230
+ }
231
+ clearSubscriptions(e) {
232
+ e ? this.subscriptions.delete(e) : this.subscriptions.clear();
233
+ }
234
+ sendPostMessage(e, t) {
235
+ let n = {
236
+ type: `encatch:${e}`,
237
+ payload: t,
238
+ source: "encatch-form-engine"
239
+ };
240
+ window.parent && window.parent !== window && window.parent.postMessage(n, this.targetOrigin), document.querySelectorAll("iframe").forEach((e) => {
241
+ e.contentWindow && e.contentWindow.postMessage(n, this.targetOrigin);
242
+ }), window.ReactNativeWebView !== void 0 && window.ReactNativeWebView.postMessage(JSON.stringify({
243
+ action: e.replace("form:", ""),
244
+ data: JSON.stringify(t)
245
+ }));
246
+ }
247
+ }();
248
+ //#endregion
249
+ //#region src/useEncatchFormEvent.ts
250
+ function s(e, t, r) {
251
+ n(() => o.subscribe(e, t, r), [
252
+ e,
253
+ r?.formId,
254
+ t
255
+ ]);
33
256
  }
34
- var N = {};
35
- /**
36
- * @license React
37
- * react-jsx-runtime.development.js
38
- *
39
- * Copyright (c) Meta Platforms, Inc. and affiliates.
40
- *
41
- * This source code is licensed under the MIT license found in the
42
- * LICENSE file in the root directory of this source tree.
43
- */
44
- var ee;
45
- function se() {
46
- return ee || (ee = 1, process.env.NODE_ENV !== "production" && (function() {
47
- function u(e) {
48
- if (e == null) return null;
49
- if (typeof e == "function")
50
- return e.$$typeof === C ? null : e.displayName || e.name || null;
51
- if (typeof e == "string") return e;
52
- switch (e) {
53
- case A:
54
- return "Fragment";
55
- case Y:
56
- return "Profiler";
57
- case P:
58
- return "StrictMode";
59
- case $:
60
- return "Suspense";
61
- case x:
62
- return "SuspenseList";
63
- case E:
64
- return "Activity";
65
- }
66
- if (typeof e == "object")
67
- switch (typeof e.tag == "number" && console.error(
68
- "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
69
- ), e.$$typeof) {
70
- case i:
71
- return "Portal";
72
- case d:
73
- return (e.displayName || "Context") + ".Provider";
74
- case c:
75
- return (e._context.displayName || "Context") + ".Consumer";
76
- case F:
77
- var t = e.render;
78
- return e = e.displayName, e || (e = t.displayName || t.name || "", e = e !== "" ? "ForwardRef(" + e + ")" : "ForwardRef"), e;
79
- case M:
80
- return t = e.displayName || null, t !== null ? t : u(e.type) || "Memo";
81
- case D:
82
- t = e._payload, e = e._init;
83
- try {
84
- return u(e(t));
85
- } catch {
86
- }
87
- }
88
- return null;
89
- }
90
- function r(e) {
91
- return "" + e;
92
- }
93
- function n(e) {
94
- try {
95
- r(e);
96
- var t = !1;
97
- } catch {
98
- t = !0;
99
- }
100
- if (t) {
101
- t = console;
102
- var l = t.error, b = typeof Symbol == "function" && Symbol.toStringTag && e[Symbol.toStringTag] || e.constructor.name || "Object";
103
- return l.call(
104
- t,
105
- "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
106
- b
107
- ), r(e);
108
- }
109
- }
110
- function a(e) {
111
- if (e === A) return "<>";
112
- if (typeof e == "object" && e !== null && e.$$typeof === D)
113
- return "<...>";
114
- try {
115
- var t = u(e);
116
- return t ? "<" + t + ">" : "<...>";
117
- } catch {
118
- return "<...>";
119
- }
120
- }
121
- function s() {
122
- var e = v.A;
123
- return e === null ? null : e.getOwner();
124
- }
125
- function f() {
126
- return Error("react-stack-top-frame");
127
- }
128
- function m(e) {
129
- if (o.call(e, "key")) {
130
- var t = Object.getOwnPropertyDescriptor(e, "key").get;
131
- if (t && t.isReactWarning) return !1;
132
- }
133
- return e.key !== void 0;
134
- }
135
- function w(e, t) {
136
- function l() {
137
- B || (B = !0, console.error(
138
- "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",
139
- t
140
- ));
141
- }
142
- l.isReactWarning = !0, Object.defineProperty(e, "key", {
143
- get: l,
144
- configurable: !0
145
- });
146
- }
147
- function k() {
148
- var e = u(this.type);
149
- return Q[e] || (Q[e] = !0, console.error(
150
- "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
151
- )), e = this.props.ref, e !== void 0 ? e : null;
152
- }
153
- function _(e, t, l, b, y, g, U, J) {
154
- return l = g.ref, e = {
155
- $$typeof: I,
156
- type: e,
157
- key: t,
158
- props: g,
159
- _owner: y
160
- }, (l !== void 0 ? l : null) !== null ? Object.defineProperty(e, "ref", {
161
- enumerable: !1,
162
- get: k
163
- }) : Object.defineProperty(e, "ref", { enumerable: !1, value: null }), e._store = {}, Object.defineProperty(e._store, "validated", {
164
- configurable: !1,
165
- enumerable: !1,
166
- writable: !0,
167
- value: 0
168
- }), Object.defineProperty(e, "_debugInfo", {
169
- configurable: !1,
170
- enumerable: !1,
171
- writable: !0,
172
- value: null
173
- }), Object.defineProperty(e, "_debugStack", {
174
- configurable: !1,
175
- enumerable: !1,
176
- writable: !0,
177
- value: U
178
- }), Object.defineProperty(e, "_debugTask", {
179
- configurable: !1,
180
- enumerable: !1,
181
- writable: !0,
182
- value: J
183
- }), Object.freeze && (Object.freeze(e.props), Object.freeze(e)), e;
184
- }
185
- function h(e, t, l, b, y, g, U, J) {
186
- var p = t.children;
187
- if (p !== void 0)
188
- if (b)
189
- if (ne(p)) {
190
- for (b = 0; b < p.length; b++)
191
- S(p[b]);
192
- Object.freeze && Object.freeze(p);
193
- } else
194
- console.error(
195
- "React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."
196
- );
197
- else S(p);
198
- if (o.call(t, "key")) {
199
- p = u(e);
200
- var O = Object.keys(t).filter(function(oe) {
201
- return oe !== "key";
202
- });
203
- b = 0 < O.length ? "{key: someKey, " + O.join(": ..., ") + ": ...}" : "{key: someKey}", Z[p + b] || (O = 0 < O.length ? "{" + O.join(": ..., ") + ": ...}" : "{}", console.error(
204
- `A props object containing a "key" prop is being spread into JSX:
205
- let props = %s;
206
- <%s {...props} />
207
- React keys must be passed directly to JSX without using spread:
208
- let props = %s;
209
- <%s key={someKey} {...props} />`,
210
- b,
211
- p,
212
- O,
213
- p
214
- ), Z[p + b] = !0);
215
- }
216
- if (p = null, l !== void 0 && (n(l), p = "" + l), m(t) && (n(t.key), p = "" + t.key), "key" in t) {
217
- l = {};
218
- for (var V in t)
219
- V !== "key" && (l[V] = t[V]);
220
- } else l = t;
221
- return p && w(
222
- l,
223
- typeof e == "function" ? e.displayName || e.name || "Unknown" : e
224
- ), _(
225
- e,
226
- p,
227
- g,
228
- y,
229
- s(),
230
- l,
231
- U,
232
- J
233
- );
234
- }
235
- function S(e) {
236
- typeof e == "object" && e !== null && e.$$typeof === I && e._store && (e._store.validated = 1);
237
- }
238
- var R = G, I = Symbol.for("react.transitional.element"), i = Symbol.for("react.portal"), A = Symbol.for("react.fragment"), P = Symbol.for("react.strict_mode"), Y = Symbol.for("react.profiler"), c = Symbol.for("react.consumer"), d = Symbol.for("react.context"), F = Symbol.for("react.forward_ref"), $ = Symbol.for("react.suspense"), x = Symbol.for("react.suspense_list"), M = Symbol.for("react.memo"), D = Symbol.for("react.lazy"), E = Symbol.for("react.activity"), C = Symbol.for("react.client.reference"), v = R.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, o = Object.prototype.hasOwnProperty, ne = Array.isArray, q = console.createTask ? console.createTask : function() {
239
- return null;
240
- };
241
- R = {
242
- react_stack_bottom_frame: function(e) {
243
- return e();
244
- }
245
- };
246
- var B, Q = {}, X = R.react_stack_bottom_frame.bind(
247
- R,
248
- f
249
- )(), H = q(a(f)), Z = {};
250
- N.Fragment = A, N.jsx = function(e, t, l, b, y) {
251
- var g = 1e4 > v.recentlyCreatedOwnerStacks++;
252
- return h(
253
- e,
254
- t,
255
- l,
256
- !1,
257
- b,
258
- y,
259
- g ? Error("react-stack-top-frame") : X,
260
- g ? q(a(e)) : H
261
- );
262
- }, N.jsxs = function(e, t, l, b, y) {
263
- var g = 1e4 > v.recentlyCreatedOwnerStacks++;
264
- return h(
265
- e,
266
- t,
267
- l,
268
- !0,
269
- b,
270
- y,
271
- g ? Error("react-stack-top-frame") : X,
272
- g ? q(a(e)) : H
273
- );
274
- };
275
- })()), N;
257
+ function c(e, t) {
258
+ n(() => o.subscribeAll(e, t), [t?.formId, e]);
276
259
  }
277
- var re;
278
- function ie() {
279
- return re || (re = 1, process.env.NODE_ENV === "production" ? W.exports = ae() : W.exports = se()), W.exports;
280
- }
281
- var ce = ie();
282
- const le = ({
283
- formConfig: u,
284
- formPageUrl: r,
285
- formId: n,
286
- scale: a = 100,
287
- instanceId: s,
288
- onFormEvent: f,
289
- prefillResponses: m
290
- }) => {
291
- const w = !!(u && r), k = n ?? u?.formId ?? s ?? "preview", _ = G.useRef(null), h = G.useRef(null), S = L(!1), R = L(() => {
292
- }), I = L(m);
293
- T(() => {
294
- I.current = m;
295
- }, [m]);
296
- const i = L({});
297
- T(() => {
298
- if (!f) return;
299
- f({
300
- onSubmit: (d) => {
301
- i.current.onSubmit = d;
302
- },
303
- onShow: (d) => {
304
- i.current.onShow = d;
305
- },
306
- onClose: (d) => {
307
- i.current.onClose = d;
308
- },
309
- onSectionChange: (d) => {
310
- i.current.onSectionChange = d;
311
- },
312
- onQuestionAnswered: (d) => {
313
- i.current.onQuestionAnswered = d;
314
- },
315
- onError: (d) => {
316
- i.current.onError = d;
317
- },
318
- onRemindMeLater: (d) => {
319
- i.current.onRemindMeLater = d;
320
- }
321
- });
322
- }, [f]);
323
- const A = z(() => {
324
- if (!h.current?.contentWindow || !u) return;
325
- const c = { formId: k, scale: a, ...u };
326
- h.current.contentWindow.postMessage(
327
- { type: "sdk:formConfig", data: c },
328
- "*"
329
- );
330
- }, [u, k, a]);
331
- R.current = A;
332
- const P = z((c) => {
333
- !h.current?.contentWindow || !Object.keys(c).length || h.current.contentWindow.postMessage(
334
- { type: "sdk:prefillResponses", data: { responses: c } },
335
- "*"
336
- );
337
- }, []);
338
- T(() => {
339
- !w || !S.current || R.current();
340
- }, [w, u, A]), T(() => {
341
- !m || !S.current || P(m);
342
- }, [m, P]);
343
- const Y = z((c) => {
344
- c.style.border = "none", c.style.width = "100%", c.style.height = "100%";
345
- }, []);
346
- return T(() => {
347
- if (!w || !_.current || !u || !r) return;
348
- const c = document.createElement("div");
349
- c.className = "encatch-preview-inner", c.style.width = "100%", c.style.height = "100%", c.style.display = "flex", c.style.flexDirection = "column", c.style.justifyContent = "flex-end", c.style.overflow = "auto";
350
- const d = document.createElement("iframe"), F = new URL(r, window.location.origin), $ = u?.isFullScreen ? "shareable" : "in-app", x = new URL(`${F.pathname}/${$}`, F.origin);
351
- x.searchParams.set("formId", k), x.searchParams.set("_t", String(Date.now())), d.src = x.toString(), d.title = "Encatch form", d.setAttribute("allow", "microphone *; camera *"), Y(d), h.current = d, c.appendChild(d), _.current.appendChild(c);
352
- const M = (D) => {
353
- const E = D.data;
354
- if (!E || typeof E != "object" || !E.type) return;
355
- let C = E.type, v = E.formId, o = E.data;
356
- switch (C.startsWith("encatch:") && (C = C.replace("encatch:", ""), v = E.payload?.feedbackConfigurationId, o = E.payload), C) {
357
- case "form:resize":
358
- h.current && o && typeof o.height == "number" && (h.current.style.height = `${o.height}px`);
359
- break;
360
- case "form:fullscreen":
361
- h.current && o?.active && (h.current.style.height = "100%");
362
- break;
363
- case "form:ready":
364
- S.current = !0, R.current(), I.current && Object.keys(I.current).length && P(I.current);
365
- break;
366
- case "form:close":
367
- i.current.onClose?.({ timestamp: Date.now() });
368
- break;
369
- case "form:complete":
370
- i.current.onClose?.({ timestamp: Date.now() });
371
- break;
372
- case "form:submit":
373
- o && i.current.onSubmit && i.current.onSubmit({
374
- feedbackConfigurationId: o.feedbackConfigurationId,
375
- feedbackIdentifier: o.feedbackIdentifier,
376
- response: o.response,
377
- isPartialSubmit: o.isPartialSubmit,
378
- timestamp: Date.now()
379
- });
380
- break;
381
- case "form:show":
382
- o && i.current.onShow && i.current.onShow({
383
- feedbackConfigurationId: o.feedbackConfigurationId,
384
- feedbackIdentifier: o.feedbackIdentifier,
385
- timestamp: Date.now()
386
- });
387
- break;
388
- case "form:started":
389
- o && i.current.onShow && i.current.onShow({
390
- feedbackConfigurationId: o.feedbackConfigurationId,
391
- feedbackIdentifier: o.feedbackIdentifier,
392
- timestamp: Date.now()
393
- });
394
- break;
395
- case "form:section:change":
396
- o && i.current.onSectionChange && i.current.onSectionChange({
397
- feedbackConfigurationId: o.feedbackConfigurationId ?? v ?? "",
398
- sectionIndex: o.sectionIndex,
399
- sectionId: o.sectionId,
400
- timestamp: Date.now()
401
- });
402
- break;
403
- case "form:answered":
404
- o && i.current.onQuestionAnswered && i.current.onQuestionAnswered({
405
- feedbackConfigurationId: o.feedbackConfigurationId ?? v ?? "",
406
- questionId: o.questionId,
407
- questionType: o.questionType,
408
- answer: o.answer,
409
- timestamp: Date.now()
410
- });
411
- break;
412
- case "form:error":
413
- o && i.current.onError && i.current.onError({
414
- feedbackConfigurationId: o.feedbackConfigurationId ?? v ?? "",
415
- questionId: o.questionId,
416
- error: o.error ?? "Unknown error",
417
- timestamp: Date.now()
418
- });
419
- break;
420
- case "form:remindmelater":
421
- i.current.onRemindMeLater?.({
422
- feedbackConfigurationId: o?.feedbackConfigurationId ?? v ?? "",
423
- feedbackIdentifier: o?.feedbackIdentifier,
424
- timestamp: Date.now()
425
- });
426
- break;
427
- }
428
- };
429
- return window.addEventListener("message", M), () => {
430
- window.removeEventListener("message", M), S.current = !1, c.parentNode && c.parentNode.removeChild(c), h.current = null;
431
- };
432
- }, [w, r, k]), /* @__PURE__ */ ce.jsx(
433
- "div",
434
- {
435
- ref: _,
436
- title: "encatchPreview1",
437
- style: w ? {
438
- width: "100%",
439
- height: "100%"
440
- } : void 0
441
- }
442
- );
443
- };
444
- class ue extends EventTarget {
445
- subscriptions = /* @__PURE__ */ new Map();
446
- targetOrigin = "*";
447
- /**
448
- * Check if a form ID matches the filter
449
- */
450
- matchesFilter(r, n) {
451
- return !n || n === "*" || n === null || n === void 0 ? !0 : typeof n == "string" ? r === n : Array.isArray(n) ? n.includes(r || "") : typeof n == "function" ? n(r || "") : !1;
452
- }
453
- /**
454
- * Get form ID from payload
455
- */
456
- getFormIdFromPayload(r) {
457
- return r?.feedbackConfigurationId;
458
- }
459
- /**
460
- * Publish an event to all matching subscribers
461
- */
462
- publish(r, n, a) {
463
- typeof window < "u" && window.dispatchEvent(
464
- new CustomEvent(r, {
465
- detail: n,
466
- bubbles: !0
467
- })
468
- ), a?.usePostMessage !== !1 && this.sendPostMessage(r, n);
469
- }
470
- /**
471
- * Subscribe to form events with optional form ID filtering
472
- */
473
- subscribe(r, n, a) {
474
- const s = Symbol("subscription"), f = {
475
- eventType: r,
476
- handler: n,
477
- filter: a?.formId,
478
- id: s,
479
- once: a?.once
480
- };
481
- this.subscriptions.has(r) || this.subscriptions.set(r, []), this.subscriptions.get(r).push(f);
482
- const m = (w) => {
483
- const k = w, _ = this.getFormIdFromPayload(k.detail);
484
- this.matchesFilter(_, a?.formId) && (n(k.detail), a?.once && typeof window < "u" && window.removeEventListener(r, m));
485
- };
486
- return typeof window < "u" && window.addEventListener(r, m), () => {
487
- this.unsubscribe(s), typeof window < "u" && window.removeEventListener(r, m);
488
- };
489
- }
490
- /**
491
- * Unsubscribe by subscription ID
492
- */
493
- unsubscribe(r) {
494
- for (const [n, a] of this.subscriptions.entries()) {
495
- const s = a.findIndex((f) => f.id === r);
496
- if (s !== -1) {
497
- a.splice(s, 1), a.length === 0 && this.subscriptions.delete(n);
498
- break;
499
- }
500
- }
501
- }
502
- /**
503
- * Subscribe to all form events with optional filtering
504
- */
505
- subscribeAll(r, n) {
506
- const a = [
507
- "form:show",
508
- "form:started",
509
- "form:submit",
510
- "form:close",
511
- "form:section:change",
512
- "form:answered",
513
- "form:error",
514
- "form:remindmelater"
515
- ], s = [];
516
- return a.forEach((f) => {
517
- const m = this.subscribe(
518
- f,
519
- (w) => r(f, w),
520
- n
521
- );
522
- s.push(m);
523
- }), () => {
524
- s.forEach((f) => f());
525
- };
526
- }
527
- /**
528
- * Get active subscriptions count (for debugging)
529
- */
530
- getSubscriptionCount(r) {
531
- return r ? this.subscriptions.get(r)?.length || 0 : Array.from(this.subscriptions.values()).reduce((n, a) => n + a.length, 0);
532
- }
533
- /**
534
- * Clear all subscriptions for an event type (or all events)
535
- */
536
- clearSubscriptions(r) {
537
- r ? this.subscriptions.delete(r) : this.subscriptions.clear();
538
- }
539
- sendPostMessage(r, n) {
540
- const a = {
541
- type: `encatch:${r}`,
542
- payload: n,
543
- source: "encatch-form-engine"
544
- };
545
- window.parent && window.parent !== window && window.parent.postMessage(a, this.targetOrigin), document.querySelectorAll("iframe").forEach((s) => {
546
- s.contentWindow && s.contentWindow.postMessage(a, this.targetOrigin);
547
- }), typeof window.ReactNativeWebView < "u" && window.ReactNativeWebView.postMessage(JSON.stringify({
548
- action: r.replace("form:", ""),
549
- data: JSON.stringify(n)
550
- }));
551
- }
552
- }
553
- const te = new ue();
554
- function de(u, r, n) {
555
- T(() => te.subscribe(
556
- u,
557
- r,
558
- n
559
- ), [u, n?.formId, r]);
560
- }
561
- function me(u, r) {
562
- T(() => te.subscribeAll(u, r), [r?.formId, u]);
563
- }
564
- export {
565
- le as EncatchPreview,
566
- de as useEncatchFormEvent,
567
- me as useEncatchFormEventAll
568
- };
260
+ //#endregion
261
+ export { a as EncatchPreview, s as useEncatchFormEvent, c as useEncatchFormEventAll };
package/dist/index.umd.js CHANGED
@@ -1,22 +1 @@
1
- (function(v,m){typeof exports=="object"&&typeof module<"u"?m(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],m):(v=typeof globalThis<"u"?globalThis:v||self,m(v.WsReact={},v.React))})(this,(function(v,m){"use strict";var M={exports:{}},x={};/**
2
- * @license React
3
- * react-jsx-runtime.production.js
4
- *
5
- * Copyright (c) Meta Platforms, Inc. and affiliates.
6
- *
7
- * This source code is licensed under the MIT license found in the
8
- * LICENSE file in the root directory of this source tree.
9
- */var z;function re(){if(z)return x;z=1;var u=Symbol.for("react.transitional.element"),r=Symbol.for("react.fragment");function n(s,a,f){var b=null;if(f!==void 0&&(b=""+f),a.key!==void 0&&(b=""+a.key),"key"in a){f={};for(var h in a)h!=="key"&&(f[h]=a[h])}else f=a;return a=f.ref,{$$typeof:u,type:s,key:b,ref:a!==void 0?a:null,props:f}}return x.Fragment=r,x.jsx=n,x.jsxs=n,x}var j={};/**
10
- * @license React
11
- * react-jsx-runtime.development.js
12
- *
13
- * Copyright (c) Meta Platforms, Inc. and affiliates.
14
- *
15
- * This source code is licensed under the MIT license found in the
16
- * LICENSE file in the root directory of this source tree.
17
- */var G;function te(){return G||(G=1,process.env.NODE_ENV!=="production"&&(function(){function u(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===O?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case C:return"Fragment";case Y:return"Profiler";case N:return"StrictMode";case $:return"Suspense";case F:return"SuspenseList";case g:return"Activity"}if(typeof e=="object")switch(typeof e.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case i:return"Portal";case d:return(e.displayName||"Context")+".Provider";case c:return(e._context.displayName||"Context")+".Consumer";case D:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case L:return t=e.displayName||null,t!==null?t:u(e.type)||"Memo";case W:t=e._payload,e=e._init;try{return u(e(t))}catch{}}return null}function r(e){return""+e}function n(e){try{r(e);var t=!1}catch{t=!0}if(t){t=console;var l=t.error,p=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return l.call(t,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",p),r(e)}}function s(e){if(e===C)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===W)return"<...>";try{var t=u(e);return t?"<"+t+">":"<...>"}catch{return"<...>"}}function a(){var e=R.A;return e===null?null:e.getOwner()}function f(){return Error("react-stack-top-frame")}function b(e){if(o.call(e,"key")){var t=Object.getOwnPropertyDescriptor(e,"key").get;if(t&&t.isReactWarning)return!1}return e.key!==void 0}function h(e,t){function l(){X||(X=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",t))}l.isReactWarning=!0,Object.defineProperty(e,"key",{get:l,configurable:!0})}function y(){var e=u(this.type);return H[e]||(H[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),e=this.props.ref,e!==void 0?e:null}function T(e,t,l,p,S,k,U,J){return l=k.ref,e={$$typeof:A,type:e,key:t,props:k,_owner:S},(l!==void 0?l:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:y}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:U}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:J}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function E(e,t,l,p,S,k,U,J){var w=t.children;if(w!==void 0)if(p)if(ue(w)){for(p=0;p<w.length;p++)I(w[p]);Object.freeze&&Object.freeze(w)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else I(w);if(o.call(t,"key")){w=u(e);var P=Object.keys(t).filter(function(fe){return fe!=="key"});p=0<P.length?"{key: someKey, "+P.join(": ..., ")+": ...}":"{key: someKey}",ee[w+p]||(P=0<P.length?"{"+P.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
18
- let props = %s;
19
- <%s {...props} />
20
- React keys must be passed directly to JSX without using spread:
21
- let props = %s;
22
- <%s key={someKey} {...props} />`,p,w,P,w),ee[w+p]=!0)}if(w=null,l!==void 0&&(n(l),w=""+l),b(t)&&(n(t.key),w=""+t.key),"key"in t){l={};for(var V in t)V!=="key"&&(l[V]=t[V])}else l=t;return w&&h(l,typeof e=="function"?e.displayName||e.name||"Unknown":e),T(e,w,k,S,a(),l,U,J)}function I(e){typeof e=="object"&&e!==null&&e.$$typeof===A&&e._store&&(e._store.validated=1)}var _=m,A=Symbol.for("react.transitional.element"),i=Symbol.for("react.portal"),C=Symbol.for("react.fragment"),N=Symbol.for("react.strict_mode"),Y=Symbol.for("react.profiler"),c=Symbol.for("react.consumer"),d=Symbol.for("react.context"),D=Symbol.for("react.forward_ref"),$=Symbol.for("react.suspense"),F=Symbol.for("react.suspense_list"),L=Symbol.for("react.memo"),W=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),O=Symbol.for("react.client.reference"),R=_.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,o=Object.prototype.hasOwnProperty,ue=Array.isArray,q=console.createTask?console.createTask:function(){return null};_={react_stack_bottom_frame:function(e){return e()}};var X,H={},Z=_.react_stack_bottom_frame.bind(_,f)(),K=q(s(f)),ee={};j.Fragment=C,j.jsx=function(e,t,l,p,S){var k=1e4>R.recentlyCreatedOwnerStacks++;return E(e,t,l,!1,p,S,k?Error("react-stack-top-frame"):Z,k?q(s(e)):K)},j.jsxs=function(e,t,l,p,S){var k=1e4>R.recentlyCreatedOwnerStacks++;return E(e,t,l,!0,p,S,k?Error("react-stack-top-frame"):Z,k?q(s(e)):K)}})()),j}var B;function ne(){return B||(B=1,process.env.NODE_ENV==="production"?M.exports=re():M.exports=te()),M.exports}var oe=ne();const se=({formConfig:u,formPageUrl:r,formId:n,scale:s=100,instanceId:a,onFormEvent:f,prefillResponses:b})=>{const h=!!(u&&r),y=n??u?.formId??a??"preview",T=m.useRef(null),E=m.useRef(null),I=m.useRef(!1),_=m.useRef(()=>{}),A=m.useRef(b);m.useEffect(()=>{A.current=b},[b]);const i=m.useRef({});m.useEffect(()=>{if(!f)return;f({onSubmit:d=>{i.current.onSubmit=d},onShow:d=>{i.current.onShow=d},onClose:d=>{i.current.onClose=d},onSectionChange:d=>{i.current.onSectionChange=d},onQuestionAnswered:d=>{i.current.onQuestionAnswered=d},onError:d=>{i.current.onError=d},onRemindMeLater:d=>{i.current.onRemindMeLater=d}})},[f]);const C=m.useCallback(()=>{if(!E.current?.contentWindow||!u)return;const c={formId:y,scale:s,...u};E.current.contentWindow.postMessage({type:"sdk:formConfig",data:c},"*")},[u,y,s]);_.current=C;const N=m.useCallback(c=>{!E.current?.contentWindow||!Object.keys(c).length||E.current.contentWindow.postMessage({type:"sdk:prefillResponses",data:{responses:c}},"*")},[]);m.useEffect(()=>{!h||!I.current||_.current()},[h,u,C]),m.useEffect(()=>{!b||!I.current||N(b)},[b,N]);const Y=m.useCallback(c=>{c.style.border="none",c.style.width="100%",c.style.height="100%"},[]);return m.useEffect(()=>{if(!h||!T.current||!u||!r)return;const c=document.createElement("div");c.className="encatch-preview-inner",c.style.width="100%",c.style.height="100%",c.style.display="flex",c.style.flexDirection="column",c.style.justifyContent="flex-end",c.style.overflow="auto";const d=document.createElement("iframe"),D=new URL(r,window.location.origin),$=u?.isFullScreen?"shareable":"in-app",F=new URL(`${D.pathname}/${$}`,D.origin);F.searchParams.set("formId",y),F.searchParams.set("_t",String(Date.now())),d.src=F.toString(),d.title="Encatch form",d.setAttribute("allow","microphone *; camera *"),Y(d),E.current=d,c.appendChild(d),T.current.appendChild(c);const L=W=>{const g=W.data;if(!g||typeof g!="object"||!g.type)return;let O=g.type,R=g.formId,o=g.data;switch(O.startsWith("encatch:")&&(O=O.replace("encatch:",""),R=g.payload?.feedbackConfigurationId,o=g.payload),O){case"form:resize":E.current&&o&&typeof o.height=="number"&&(E.current.style.height=`${o.height}px`);break;case"form:fullscreen":E.current&&o?.active&&(E.current.style.height="100%");break;case"form:ready":I.current=!0,_.current(),A.current&&Object.keys(A.current).length&&N(A.current);break;case"form:close":i.current.onClose?.({timestamp:Date.now()});break;case"form:complete":i.current.onClose?.({timestamp:Date.now()});break;case"form:submit":o&&i.current.onSubmit&&i.current.onSubmit({feedbackConfigurationId:o.feedbackConfigurationId,feedbackIdentifier:o.feedbackIdentifier,response:o.response,isPartialSubmit:o.isPartialSubmit,timestamp:Date.now()});break;case"form:show":o&&i.current.onShow&&i.current.onShow({feedbackConfigurationId:o.feedbackConfigurationId,feedbackIdentifier:o.feedbackIdentifier,timestamp:Date.now()});break;case"form:started":o&&i.current.onShow&&i.current.onShow({feedbackConfigurationId:o.feedbackConfigurationId,feedbackIdentifier:o.feedbackIdentifier,timestamp:Date.now()});break;case"form:section:change":o&&i.current.onSectionChange&&i.current.onSectionChange({feedbackConfigurationId:o.feedbackConfigurationId??R??"",sectionIndex:o.sectionIndex,sectionId:o.sectionId,timestamp:Date.now()});break;case"form:answered":o&&i.current.onQuestionAnswered&&i.current.onQuestionAnswered({feedbackConfigurationId:o.feedbackConfigurationId??R??"",questionId:o.questionId,questionType:o.questionType,answer:o.answer,timestamp:Date.now()});break;case"form:error":o&&i.current.onError&&i.current.onError({feedbackConfigurationId:o.feedbackConfigurationId??R??"",questionId:o.questionId,error:o.error??"Unknown error",timestamp:Date.now()});break;case"form:remindmelater":i.current.onRemindMeLater?.({feedbackConfigurationId:o?.feedbackConfigurationId??R??"",feedbackIdentifier:o?.feedbackIdentifier,timestamp:Date.now()});break}};return window.addEventListener("message",L),()=>{window.removeEventListener("message",L),I.current=!1,c.parentNode&&c.parentNode.removeChild(c),E.current=null}},[h,r,y]),oe.jsx("div",{ref:T,title:"encatchPreview1",style:h?{width:"100%",height:"100%"}:void 0})};class ae extends EventTarget{subscriptions=new Map;targetOrigin="*";matchesFilter(r,n){return!n||n==="*"||n===null||n===void 0?!0:typeof n=="string"?r===n:Array.isArray(n)?n.includes(r||""):typeof n=="function"?n(r||""):!1}getFormIdFromPayload(r){return r?.feedbackConfigurationId}publish(r,n,s){typeof window<"u"&&window.dispatchEvent(new CustomEvent(r,{detail:n,bubbles:!0})),s?.usePostMessage!==!1&&this.sendPostMessage(r,n)}subscribe(r,n,s){const a=Symbol("subscription"),f={eventType:r,handler:n,filter:s?.formId,id:a,once:s?.once};this.subscriptions.has(r)||this.subscriptions.set(r,[]),this.subscriptions.get(r).push(f);const b=h=>{const y=h,T=this.getFormIdFromPayload(y.detail);this.matchesFilter(T,s?.formId)&&(n(y.detail),s?.once&&typeof window<"u"&&window.removeEventListener(r,b))};return typeof window<"u"&&window.addEventListener(r,b),()=>{this.unsubscribe(a),typeof window<"u"&&window.removeEventListener(r,b)}}unsubscribe(r){for(const[n,s]of this.subscriptions.entries()){const a=s.findIndex(f=>f.id===r);if(a!==-1){s.splice(a,1),s.length===0&&this.subscriptions.delete(n);break}}}subscribeAll(r,n){const s=["form:show","form:started","form:submit","form:close","form:section:change","form:answered","form:error","form:remindmelater"],a=[];return s.forEach(f=>{const b=this.subscribe(f,h=>r(f,h),n);a.push(b)}),()=>{a.forEach(f=>f())}}getSubscriptionCount(r){return r?this.subscriptions.get(r)?.length||0:Array.from(this.subscriptions.values()).reduce((n,s)=>n+s.length,0)}clearSubscriptions(r){r?this.subscriptions.delete(r):this.subscriptions.clear()}sendPostMessage(r,n){const s={type:`encatch:${r}`,payload:n,source:"encatch-form-engine"};window.parent&&window.parent!==window&&window.parent.postMessage(s,this.targetOrigin),document.querySelectorAll("iframe").forEach(a=>{a.contentWindow&&a.contentWindow.postMessage(s,this.targetOrigin)}),typeof window.ReactNativeWebView<"u"&&window.ReactNativeWebView.postMessage(JSON.stringify({action:r.replace("form:",""),data:JSON.stringify(n)}))}}const Q=new ae;function ie(u,r,n){m.useEffect(()=>Q.subscribe(u,r,n),[u,n?.formId,r])}function ce(u,r){m.useEffect(()=>Q.subscribeAll(u,r),[r?.formId,u])}v.EncatchPreview=se,v.useEncatchFormEvent=ie,v.useEncatchFormEventAll=ce,Object.defineProperty(v,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require(`react`),require(`react/jsx-runtime`)):typeof define==`function`&&define.amd?define([`exports`,`react`,`react/jsx-runtime`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.WsReact={},e.React,e.ReactJsxRuntime))})(this,function(e,t,n){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var r=Object.create,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var s=o(t),l=0,u=s.length,d;l<u;l++)d=s[l],!c.call(e,d)&&d!==n&&i(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(r=a(t,d))||r.enumerable});return e};t=((e,t,n)=>(n=e==null?{}:r(s(e)),l(t||!e||!e.__esModule?i(n,`default`,{value:e,enumerable:!0}):n,e)))(t,1);var u=({formConfig:e,formPageUrl:r,formId:i,scale:a=100,instanceId:o,onFormEvent:s,prefillResponses:c})=>{let l=!!(e&&r),u=i??e?.formId??o??`preview`,d=t.default.useRef(null),f=t.default.useRef(null),p=(0,t.useRef)(!1),m=(0,t.useRef)(()=>{}),h=(0,t.useRef)(c);(0,t.useEffect)(()=>{h.current=c},[c]);let g=(0,t.useRef)({});(0,t.useEffect)(()=>{s&&s({onSubmit:e=>{g.current.onSubmit=e},onShow:e=>{g.current.onShow=e},onClose:e=>{g.current.onClose=e},onSectionChange:e=>{g.current.onSectionChange=e},onQuestionAnswered:e=>{g.current.onQuestionAnswered=e},onError:e=>{g.current.onError=e},onRemindMeLater:e=>{g.current.onRemindMeLater=e}})},[s]);let _=(0,t.useCallback)(()=>{if(!f.current?.contentWindow||!e)return;let t={formId:u,scale:a,...e};f.current.contentWindow.postMessage({type:`sdk:formConfig`,data:t},`*`)},[e,u,a]);m.current=_;let v=(0,t.useCallback)(e=>{!f.current?.contentWindow||!Object.keys(e).length||f.current.contentWindow.postMessage({type:`sdk:prefillResponses`,data:{responses:e}},`*`)},[]);(0,t.useEffect)(()=>{!l||!p.current||m.current()},[l,e,_]),(0,t.useEffect)(()=>{!c||!p.current||v(c)},[c,v]);let y=(0,t.useCallback)(e=>{e.style.border=`none`,e.style.width=`100%`,e.style.height=`100%`},[]);return(0,t.useEffect)(()=>{if(!l||!d.current||!e||!r)return;let t=document.createElement(`div`);t.className=`encatch-preview-inner`,t.style.width=`100%`,t.style.height=`100%`,t.style.display=`flex`,t.style.flexDirection=`column`,t.style.justifyContent=`flex-end`,t.style.overflow=`auto`;let n=document.createElement(`iframe`),i=new URL(r,window.location.origin),a=e?.isFullScreen?`shareable`:`in-app`,o=new URL(`${i.pathname}/${a}`,i.origin);o.searchParams.set(`formId`,u),o.searchParams.set(`_t`,String(Date.now())),n.src=o.toString(),n.title=`Encatch form`,n.setAttribute(`allow`,`microphone *; camera *`),y(n),f.current=n,t.appendChild(n),d.current.appendChild(t);let s=e=>{let t=e.data;if(!t||typeof t!=`object`||!t.type)return;let n=t.type,r=t.formId,i=t.data;switch(n.startsWith(`encatch:`)&&(n=n.replace(`encatch:`,``),r=t.payload?.feedbackConfigurationId,i=t.payload),n){case`form:resize`:f.current&&i&&typeof i.height==`number`&&(f.current.style.height=`${i.height}px`);break;case`form:fullscreen`:f.current&&i?.active&&(f.current.style.height=`100%`);break;case`form:ready`:p.current=!0,m.current(),h.current&&Object.keys(h.current).length&&v(h.current);break;case`form:close`:g.current.onClose?.({timestamp:Date.now()});break;case`form:complete`:g.current.onClose?.({timestamp:Date.now()});break;case`form:submit`:i&&g.current.onSubmit&&g.current.onSubmit({feedbackConfigurationId:i.feedbackConfigurationId,feedbackIdentifier:i.feedbackIdentifier,response:i.response,isPartialSubmit:i.isPartialSubmit,timestamp:Date.now()});break;case`form:show`:i&&g.current.onShow&&g.current.onShow({feedbackConfigurationId:i.feedbackConfigurationId,feedbackIdentifier:i.feedbackIdentifier,timestamp:Date.now()});break;case`form:started`:i&&g.current.onShow&&g.current.onShow({feedbackConfigurationId:i.feedbackConfigurationId,feedbackIdentifier:i.feedbackIdentifier,timestamp:Date.now()});break;case`form:section:change`:i&&g.current.onSectionChange&&g.current.onSectionChange({feedbackConfigurationId:i.feedbackConfigurationId??r??``,sectionIndex:i.sectionIndex,sectionId:i.sectionId,timestamp:Date.now()});break;case`form:answered`:i&&g.current.onQuestionAnswered&&g.current.onQuestionAnswered({feedbackConfigurationId:i.feedbackConfigurationId??r??``,questionId:i.questionId,questionType:i.questionType,answer:i.answer,timestamp:Date.now()});break;case`form:error`:i&&g.current.onError&&g.current.onError({feedbackConfigurationId:i.feedbackConfigurationId??r??``,questionId:i.questionId,error:i.error??`Unknown error`,timestamp:Date.now()});break;case`form:remindmelater`:g.current.onRemindMeLater?.({feedbackConfigurationId:i?.feedbackConfigurationId??r??``,feedbackIdentifier:i?.feedbackIdentifier,timestamp:Date.now()});break;default:break}};return window.addEventListener(`message`,s),()=>{window.removeEventListener(`message`,s),p.current=!1,t.parentNode&&t.parentNode.removeChild(t),f.current=null}},[l,r,u]),(0,n.jsx)(`div`,{ref:d,title:`encatchPreview1`,style:l?{width:`100%`,height:`100%`}:void 0})},d=new class extends EventTarget{subscriptions=new Map;targetOrigin=`*`;matchesFilter(e,t){return!t||t===`*`||t==null?!0:typeof t==`string`?e===t:Array.isArray(t)?t.includes(e||``):typeof t==`function`?t(e||``):!1}getFormIdFromPayload(e){return e?.feedbackConfigurationId}publish(e,t,n){typeof window<`u`&&window.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0})),n?.usePostMessage!==!1&&this.sendPostMessage(e,t)}subscribe(e,t,n){let r=Symbol(`subscription`),i={eventType:e,handler:t,filter:n?.formId,id:r,once:n?.once};this.subscriptions.has(e)||this.subscriptions.set(e,[]),this.subscriptions.get(e).push(i);let a=r=>{let i=r,o=this.getFormIdFromPayload(i.detail);this.matchesFilter(o,n?.formId)&&(t(i.detail),n?.once&&typeof window<`u`&&window.removeEventListener(e,a))};return typeof window<`u`&&window.addEventListener(e,a),()=>{this.unsubscribe(r),typeof window<`u`&&window.removeEventListener(e,a)}}unsubscribe(e){for(let[t,n]of this.subscriptions.entries()){let r=n.findIndex(t=>t.id===e);if(r!==-1){n.splice(r,1),n.length===0&&this.subscriptions.delete(t);break}}}subscribeAll(e,t){let n=[`form:show`,`form:started`,`form:submit`,`form:close`,`form:section:change`,`form:answered`,`form:error`,`form:remindmelater`],r=[];return n.forEach(n=>{let i=this.subscribe(n,t=>e(n,t),t);r.push(i)}),()=>{r.forEach(e=>e())}}getSubscriptionCount(e){return e?this.subscriptions.get(e)?.length||0:Array.from(this.subscriptions.values()).reduce((e,t)=>e+t.length,0)}clearSubscriptions(e){e?this.subscriptions.delete(e):this.subscriptions.clear()}sendPostMessage(e,t){let n={type:`encatch:${e}`,payload:t,source:`encatch-form-engine`};window.parent&&window.parent!==window&&window.parent.postMessage(n,this.targetOrigin),document.querySelectorAll(`iframe`).forEach(e=>{e.contentWindow&&e.contentWindow.postMessage(n,this.targetOrigin)}),window.ReactNativeWebView!==void 0&&window.ReactNativeWebView.postMessage(JSON.stringify({action:e.replace(`form:`,``),data:JSON.stringify(t)}))}};function f(e,n,r){(0,t.useEffect)(()=>d.subscribe(e,n,r),[e,r?.formId,n])}function p(e,n){(0,t.useEffect)(()=>d.subscribeAll(e,n),[n?.formId,e])}e.EncatchPreview=u,e.useEncatchFormEvent=f,e.useEncatchFormEventAll=p});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@encatch/ws-react",
3
- "version": "0.2.1-beta.9",
3
+ "version": "0.2.1",
4
4
  "type": "module",
5
5
  "main": "./dist/index.umd.js",
6
6
  "module": "./dist/index.es.js",
@@ -20,24 +20,24 @@
20
20
  "react-dom": "^19.1.1"
21
21
  },
22
22
  "dependencies": {
23
- "@encatch/schema": "1.2.0-beta.12",
24
- "@encatch/event-publisher": "1.0.2-beta.1"
23
+ "@encatch/event-publisher": "1.0.2",
24
+ "@encatch/schema": "1.2.0"
25
25
  },
26
26
  "devDependencies": {
27
- "@eslint/js": "^9.36.0",
28
- "@types/node": "^24.10.0",
29
- "@types/react": "^19.1.16",
30
- "@types/react-dom": "^19.1.9",
31
- "@vitejs/plugin-react": "^5.0.4",
32
- "eslint": "^9.36.0",
33
- "eslint-plugin-react-hooks": "^5.2.0",
34
- "eslint-plugin-react-refresh": "^0.4.22",
35
- "globals": "^16.4.0",
36
- "react": "^19.1.1",
37
- "react-dom": "^19.1.1",
38
- "typescript": "~5.9.3",
39
- "typescript-eslint": "^8.45.0",
40
- "vite": "^7.1.7",
27
+ "@eslint/js": "^10.0.1",
28
+ "@types/node": "^25.7.0",
29
+ "@types/react": "^19.2.14",
30
+ "@types/react-dom": "^19.2.3",
31
+ "@vitejs/plugin-react": "^6.0.1",
32
+ "eslint": "^10.3.0",
33
+ "eslint-plugin-react-hooks": "^7.1.1",
34
+ "eslint-plugin-react-refresh": "^0.5.2",
35
+ "globals": "^17.6.0",
36
+ "react": "^19.2.6",
37
+ "react-dom": "^19.2.6",
38
+ "typescript": "~6.0.3",
39
+ "typescript-eslint": "^8.59.3",
40
+ "vite": "^8.0.12",
41
41
  "@encatch/web-form-engine-core": "0.0.0"
42
42
  },
43
43
  "scripts": {