@cowprotocol/widget-react 0.3.0 → 0.4.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/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var l=Object.defineProperty;var E=(n,e,t)=>e in n?l(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var c=(n,e,t)=>(E(n,typeof e!="symbol"?e+"":e,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const W=require("react/jsx-runtime"),i=require("react"),R="2.0",P="*",v=["connect","disconnect","close","chainChanged","accountsChanged"];class S{constructor(e){c(this,"ethereumProvider",null);c(this,"requests",{});c(this,"processEvent",e=>{e.data.jsonrpc==="2.0"&&(this.ethereumProvider?this.processRequest(e.data):this.requests[e.data.id]=e.data)});this.contentWindow=e,window.addEventListener("message",this.processEvent)}disconnect(){this.ethereumProvider=null,window.removeEventListener("message",this.processEvent)}onConnect(e){this.ethereumProvider=e,Object.keys(this.requests).forEach(t=>{this.processRequest(this.requests[t])}),this.requests={},v.forEach(t=>{e.on(t,s=>{this.postMessage({method:t,params:[s]})})})}processRequest(e){if(!this.ethereumProvider)return;(e.method==="enable"?this.ethereumProvider.enable():this.ethereumProvider.request(e)).then(s=>{this.postMessage({id:e.id,result:s})}).catch(s=>{this.postMessage({id:e.id,error:s})})}postMessage(e){this.contentWindow.postMessage({jsonrpc:R,...e},P)}}function y(){return typeof window>"u"||!window?"":`https://swap-dev-git-${window.location.hostname.replace("widget-configurator-git-","").replace("-cowswap.vercel.app","")}-cowswap.vercel.app`}const p={local:"http://localhost:3000",prod:"https://swap.cow.fi",dev:"https://dev.swap.cow.fi",pr:y()};var d=(n=>(n.SWAP="swap",n.LIMIT="limit",n.ADVANCED="advanced",n))(d||{});const u="_";function T(n){const e=p[n.env||"prod"],t=f(n),s=w(n);return e+"/#"+t+"?"+s}function f(n){const{chainId:e=1,sell:t,buy:s,tradeType:o=d.SWAP}=n,r=[(t==null?void 0:t.asset)||u,(s==null?void 0:s.asset)||u].map(encodeURIComponent).join("/");return`/${e}/widget/${o}/${r}`}function w(n){const{sell:e,buy:t,theme:s}=n,o=new URLSearchParams;return e!=null&&e.amount&&o.append("sellAmount",e.amount),t!=null&&t.amount&&o.append("buyAmount",t.amount),s&&o.append("theme",typeof s=="string"?s:s.baseTheme),o}const a="cowSwapWidget",g="640px",C="450px",A=20;function m(n,e={}){const{provider:t}=e,s=M(e);n.innerHTML="",n.appendChild(s);const{contentWindow:o}=s;if(!o)throw new Error("Iframe does not contain a window!");return _(o,e.appCode),L(s,e.height),t&&new S(o).onConnect(t),s.addEventListener("load",()=>{h(e,o)}),r=>h(r,o)}function M(n){const{width:e=C,height:t=g}=n,s=document.createElement("iframe");return s.src=T(n),s.width=e,s.height=t,s.style.border="0",s}function h(n,e){const t=f(n),s=w(n).toString();e.postMessage({key:a,method:"update",urlParams:{pathname:t,search:s},appParams:{...n,provider:void 0}},"*")}function _(n,e){window.addEventListener("message",t=>{t.data.key!==a||t.data.method!=="activate"||n.postMessage({key:a,method:"metaData",metaData:e?{appCode:e}:void 0},"*")})}function L(n,e=g){window.addEventListener("message",t=>{t.data.key!==a||t.data.method!=="iframeHeight"||(n.style.height=t.data.height?`${t.data.height+A}px`:e)})}function q({params:n,provider:e}){const t=i.useRef(),s=i.useRef(null),o=i.useRef(null);return i.useEffect(()=>{s.current&&(e&&t.current!==e&&(o.current=null),o.current?o.current(n):o.current=m(s.current,n))},[e,n]),i.useEffect(()=>{t.current=e},[e]),W.jsx("div",{ref:s})}exports.COWSWAP_URLS=p;exports.CowSwapWidget=q;exports.TradeType=d;exports.cowSwapWidget=m;
1
+ "use strict";var N=Object.defineProperty;var H=(n,e,t)=>e in n?N(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var h=(n,e,t)=>(H(n,typeof e!="symbol"?e+"":e,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const g=require("react/jsx-runtime"),u=require("react"),D="cowSwapWidget";function R(n,e,t){const s={key:D,method:e,...typeof t=="object"?t:{}};n.postMessage(s,"*")}function P(n,e,t){const r=s=>{!b(s.data)||s.data.key!==D||s.data.method!==e||t(s.data)};return n.addEventListener("message",r),r}function b(n){return typeof n=="object"&&n!==null&&"key"in n&&"method"in n&&typeof n.key=="string"&&typeof n.method=="string"}function O(n,e,t){n.removeEventListener("message",t)}function _(n,e){n.removeEventListener("message",e)}var l=(n=>(n.ACTIVATE="ACTIVATE",n.UPDATE_HEIGHT="UPDATE_HEIGHT",n.EMIT_COW_EVENT="EMIT_COW_EVENT",n.PROVIDER_RPC_REQUEST="PROVIDER_RPC_REQUEST",n))(l||{}),m=(n=>(n.UPDATE_PARAMS="UPDATE_PARAMS",n.UPDATE_APP_DATA="UPDATE_APP_DATA",n.PROVIDER_RPC_RESPONSE="PROVIDER_RPC_RESPONSE",n.PROVIDER_ON_EVENT="PROVIDER_ON_EVENT",n))(m||{}),v=(n=>(n.SWAP="swap",n.LIMIT="limit",n.ADVANCED="advanced",n))(v||{});const F=["connect","disconnect","close","chainChanged","accountsChanged"];class M{constructor(e){h(this,"ethereumProvider",null);h(this,"requestWaitingForConnection",{});h(this,"processRpcCallFromWindow",({rpcRequest:e})=>{if(!this.ethereumProvider){e.id&&(this.requestWaitingForConnection[e.id]=e);return}this.processRpcRequest(e)});this.iframeWidow=e}disconnect(){this.ethereumProvider=null,O(window,l.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow)}onConnect(e){this.ethereumProvider?this.disconnect():P(window,l.PROVIDER_RPC_REQUEST,this.processRpcCallFromWindow),this.ethereumProvider=e,this.processPendingRequests(),F.forEach(t=>{e.on(t,r=>this.onProviderEvent(t,r))})}processPendingRequests(){Object.keys(this.requestWaitingForConnection).forEach(e=>{this.processRpcRequest(this.requestWaitingForConnection[e])}),this.requestWaitingForConnection={}}processRpcRequest(e){const{id:t,jsonrpc:r,method:s}=e;if(!this.ethereumProvider||!t)return;(s==="enable"?this.ethereumProvider.enable():this.ethereumProvider.request({...e,id:t})).then(o=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:t,result:o}})).catch(o=>this.forwardRpcResponseToIframe({rpcResponse:{jsonrpc:r,id:t,error:o}}))}onProviderEvent(e,t){R(this.iframeWidow,m.PROVIDER_ON_EVENT,{event:e,params:t})}forwardRpcResponseToIframe(e){R(this.iframeWidow,m.PROVIDER_RPC_RESPONSE,e)}}function q(){return typeof window>"u"||!window?"":`https://swap-dev-git-${window.location.hostname.replace("widget-configurator-git-","").replace("-cowswap.vercel.app","")}-cowswap.vercel.app`}const L={local:"http://localhost:3000",prod:"https://swap.cow.fi",dev:"https://dev.swap.cow.fi",pr:q()},W="_";function x(n){const e=L[n.env||"prod"],t=y(n),r=U(n);return e+"/#"+t+"?"+r}function y(n){const{chainId:e=1,sell:t,buy:r,tradeType:s=v.SWAP}=n,c=[(t==null?void 0:t.asset)||W,(r==null?void 0:r.asset)||W].map(encodeURIComponent).join("/");return`/${e}/widget/${s}/${c}`}function U(n){const{sell:e,buy:t,theme:r}=n,s=new URLSearchParams;return e!=null&&e.amount&&s.append("sellAmount",e.amount),t!=null&&t.amount&&s.append("buyAmount",t.amount),r&&s.append("theme",typeof r=="string"?r:r.baseTheme),s}class G{constructor(){h(this,"subscriptions",{})}on(e){const{event:t,handler:r}=e;this.subscriptions[t]||(this.subscriptions[t]=[]),this.subscriptions[t].push(r)}off(e){const{event:t,handler:r}=e;this.subscriptions[t]&&(this.subscriptions[t]=this.subscriptions[t].filter(s=>s!==r))}emit(e,t){this.subscriptions[e]&&this.subscriptions[e].forEach(r=>r(t))}}let $=1;class k{constructor(e,t=[]){h(this,"eventEmitter",new G);h(this,"listeners",[]);h(this,"widgetListener");h(this,"instanceNumber",$++);this.contentWindow=e,this.updateListeners(t),this.widgetListener=P(this.contentWindow,l.EMIT_COW_EVENT,r=>this.eventEmitter.emit(r.event,r.payload))}stopListeningIframe(){_(this.contentWindow,this.widgetListener)}updateListeners(e){for(const t of this.listeners)this.eventEmitter.off(t);this.listeners=e||[];for(const t of this.listeners)this.eventEmitter.on(t)}}const V="640px",j="450px",Q=20;function T(n,e){const{params:t,provider:r,listeners:s}=e;let c=r;const o=K(t);n.innerHTML="",n.appendChild(o);const{contentWindow:a}=o;if(!a)throw console.error("Iframe does not contain a window",o),new Error("Iframe does not contain a window!");const w=[];w.push(J(a,t.appCode)),w.push(Y(o,t.height));const f=new k(window,s);let d=I(a,null,c);return o.addEventListener("load",()=>S(a,t,c)),{updateParams:i=>S(a,i,c),updateListeners:i=>f.updateListeners(i),updateProvider:i=>{c=i,d=I(a,d,i)},destroy:()=>{f.stopListeningIframe(),w.forEach(i=>window.removeEventListener("message",i)),n.removeChild(o)}}}function I(n,e,t){e&&e.disconnect();const r=e||new M(n);return t&&r.onConnect(t),r}function K(n){const{width:e=j,height:t=V}=n,r=document.createElement("iframe");return r.src=x(n),r.width=e,r.height=t,r.style.border="0",r}function S(n,e,t){const r=!!t,s=y(e),c=U(e).toString();R(n,m.UPDATE_PARAMS,{urlParams:{pathname:s,search:c},appParams:{...e},hasProvider:r})}function J(n,e){const t=P(window,l.ACTIVATE,()=>{_(window,t),R(n,m.UPDATE_APP_DATA,{metaData:e?{appCode:e}:void 0})});return t}function Y(n,e=V){return P(window,l.UPDATE_HEIGHT,t=>{n.style.height=t.height?`${t.height+Q}px`:e})}function z(n){const{params:e,provider:t,listeners:r}=n,[s,c]=u.useState(null),o=u.useRef(null),a=u.useRef(t),w=u.useRef(r),f=u.useRef(null),d=u.useRef(null),i=u.useCallback((p,E)=>{try{console.log(`[WIDGET] ${p}`),E()}catch(A){const C=`Error ${p.toLowerCase()}`;console.error(`[WIDGET] ${C}`,A),c({message:C,error:A})}},[c]);return u.useEffect(()=>{if(!f.current||JSON.stringify(o.current)===JSON.stringify(e))return;const p=f.current,E=d.current;o.current=e,E===null?i("Creating a new widget",()=>{d.current=T(p,{params:e,provider:a.current,listeners:r}),w.current=r}):i("Updating the widget",()=>E.updateParams(e))},[e]),u.useEffect(()=>{if(!d.current||a.current===t)return;a.current=t;const p=f.current;p&&i("Updating the provider",()=>{var E;(E=d.current)==null||E.destroy(),d.current=T(p,{params:e,provider:a.current,listeners:r})})},[t]),u.useEffect(()=>{if(!d.current||w.current===r)return;const p=d.current;i("Updating the listeners",()=>p.updateListeners(r))},[r]),s?g.jsxs("div",{style:{color:"#ff3a3a"},children:[s.message,s.error.message&&g.jsx("pre",{style:{whiteSpace:"pre-wrap",fontSize:"0.75em"},children:s.error.message})]}):g.jsx("div",{ref:f})}exports.COWSWAP_URLS=L;exports.CowSwapWidget=z;exports.TradeType=v;exports.WidgetMethodsEmit=l;exports.WidgetMethodsListen=m;exports.createCowSwapWidget=T;exports.listenToMessageFromWindow=P;exports.postMessageToWindow=R;exports.stopListeningToMessageFromWindow=O;exports.stopListeningWindowListener=_;
package/index.mjs CHANGED
@@ -1,153 +1,279 @@
1
- var g = Object.defineProperty;
2
- var l = (n, e, t) => e in n ? g(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t;
3
- var r = (n, e, t) => (l(n, typeof e != "symbol" ? e + "" : e, t), t);
4
- import { jsx as E } from "react/jsx-runtime";
5
- import { useRef as a, useEffect as d } from "react";
6
- const v = "2.0", P = "*", W = ["connect", "disconnect", "close", "chainChanged", "accountsChanged"];
7
- class R {
1
+ var V = Object.defineProperty;
2
+ var N = (n, e, t) => e in n ? V(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t;
3
+ var p = (n, e, t) => (N(n, typeof e != "symbol" ? e + "" : e, t), t);
4
+ import { jsxs as H, jsx as v } from "react/jsx-runtime";
5
+ import { useState as b, useRef as m, useCallback as F, useEffect as g } from "react";
6
+ const W = "cowSwapWidget";
7
+ function P(n, e, t) {
8
+ const s = {
9
+ key: W,
10
+ method: e,
11
+ ...typeof t == "object" ? t : {}
12
+ };
13
+ n.postMessage(
14
+ s,
15
+ "*"
16
+ // TODO: Change to CoW specific origin in production. https://github.com/cowprotocol/cowswap/issues/3828
17
+ );
18
+ }
19
+ function R(n, e, t) {
20
+ const r = (s) => {
21
+ !q(s.data) || s.data.key !== W || s.data.method !== e || t(s.data);
22
+ };
23
+ return n.addEventListener("message", r), r;
24
+ }
25
+ function q(n) {
26
+ return typeof n == "object" && n !== null && "key" in n && "method" in n && typeof n.key == "string" && typeof n.method == "string";
27
+ }
28
+ function M(n, e, t) {
29
+ n.removeEventListener("message", t);
30
+ }
31
+ function O(n, e) {
32
+ n.removeEventListener("message", e);
33
+ }
34
+ var l = /* @__PURE__ */ ((n) => (n.ACTIVATE = "ACTIVATE", n.UPDATE_HEIGHT = "UPDATE_HEIGHT", n.EMIT_COW_EVENT = "EMIT_COW_EVENT", n.PROVIDER_RPC_REQUEST = "PROVIDER_RPC_REQUEST", n))(l || {}), w = /* @__PURE__ */ ((n) => (n.UPDATE_PARAMS = "UPDATE_PARAMS", n.UPDATE_APP_DATA = "UPDATE_APP_DATA", n.PROVIDER_RPC_RESPONSE = "PROVIDER_RPC_RESPONSE", n.PROVIDER_ON_EVENT = "PROVIDER_ON_EVENT", n))(w || {}), S = /* @__PURE__ */ ((n) => (n.SWAP = "swap", n.LIMIT = "limit", n.ADVANCED = "advanced", n))(S || {});
35
+ const G = ["connect", "disconnect", "close", "chainChanged", "accountsChanged"];
36
+ class $ {
8
37
  /**
9
- * Creates an instance of JsonRpcManager.
10
- * @param contentWindow - The window for handling events.
38
+ * Creates an instance of IframeRpcProviderBridge.
39
+ * @param iframeWidow - The iFrame window that will post up general RPC messages and to which the IframeRpcProviderBridge will forward the RPC result.
40
+ * Also it will receive some special RPC events coming from the wallet, like connect/chainChanged,accountChanged
11
41
  */
12
42
  constructor(e) {
13
43
  /**
14
44
  * The Ethereum provider instance.
15
- * When is null the JSON-RPC manager is disconnected from the Ethereum provider.
45
+ * When is null the JSON-RPC bridge is disconnected from the Ethereum provider.
16
46
  * */
17
- r(this, "ethereumProvider", null);
18
- /** Stored JSON-RPC requests. */
19
- r(this, "requests", {});
20
- r(this, "processEvent", (e) => {
21
- e.data.jsonrpc === "2.0" && (this.ethereumProvider ? this.processRequest(e.data) : this.requests[e.data.id] = e.data);
47
+ p(this, "ethereumProvider", null);
48
+ /** Stored JSON-RPC requests, to queue them when disconnected. */
49
+ p(this, "requestWaitingForConnection", {});
50
+ p(this, "processRpcCallFromWindow", ({ rpcRequest: e }) => {
51
+ if (!this.ethereumProvider) {
52
+ e.id && (this.requestWaitingForConnection[e.id] = e);
53
+ return;
54
+ }
55
+ this.processRpcRequest(e);
22
56
  });
23
- this.contentWindow = e, window.addEventListener("message", this.processEvent);
57
+ this.iframeWidow = e;
24
58
  }
25
59
  /**
26
- * Disconnects the JSON-RPC manager from the Ethereum provider.
60
+ * Disconnects the JSON-RPC bridge from the Ethereum provider.
27
61
  */
28
62
  disconnect() {
29
- this.ethereumProvider = null, window.removeEventListener("message", this.processEvent);
63
+ this.ethereumProvider = null, M(window, l.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow);
30
64
  }
31
65
  /**
32
66
  * Handles the 'connect' event and sets up event listeners for Ethereum provider events.
33
- * @param ethereumProvider - The Ethereum provider to connect.
67
+ * @param newProvider - The Ethereum provider to connect.
34
68
  */
35
69
  onConnect(e) {
36
- this.ethereumProvider = e, Object.keys(this.requests).forEach((t) => {
37
- this.processRequest(this.requests[t]);
38
- }), this.requests = {}, W.forEach((t) => {
39
- e.on(t, (o) => {
40
- this.postMessage({ method: t, params: [o] });
41
- });
70
+ this.ethereumProvider ? this.disconnect() : R(window, l.PROVIDER_RPC_REQUEST, this.processRpcCallFromWindow), this.ethereumProvider = e, this.processPendingRequests(), G.forEach((t) => {
71
+ e.on(t, (r) => this.onProviderEvent(t, r));
42
72
  });
43
73
  }
74
+ processPendingRequests() {
75
+ Object.keys(this.requestWaitingForConnection).forEach((e) => {
76
+ this.processRpcRequest(this.requestWaitingForConnection[e]);
77
+ }), this.requestWaitingForConnection = {};
78
+ }
44
79
  /**
45
80
  * Processes a JSON-RPC request and sends appropriate response or error via the content window.
46
81
  * @param request - The JSON-RPC request to be processed.
47
82
  */
48
- processRequest(e) {
49
- if (!this.ethereumProvider)
83
+ processRpcRequest(e) {
84
+ const { id: t, jsonrpc: r, method: s } = e;
85
+ if (!this.ethereumProvider || !t)
50
86
  return;
51
- (e.method === "enable" ? this.ethereumProvider.enable() : this.ethereumProvider.request(e)).then((o) => {
52
- this.postMessage({ id: e.id, result: o });
53
- }).catch((o) => {
54
- this.postMessage({ id: e.id, error: o });
87
+ (s === "enable" ? this.ethereumProvider.enable() : this.ethereumProvider.request({ ...e, id: t })).then(
88
+ (o) => this.forwardRpcResponseToIframe({
89
+ rpcResponse: { jsonrpc: r, id: t, result: o }
90
+ })
91
+ ).catch(
92
+ (o) => this.forwardRpcResponseToIframe({
93
+ rpcResponse: { jsonrpc: r, id: t, error: o }
94
+ })
95
+ );
96
+ }
97
+ onProviderEvent(e, t) {
98
+ P(this.iframeWidow, w.PROVIDER_ON_EVENT, {
99
+ event: e,
100
+ params: t
55
101
  });
56
102
  }
57
- postMessage(e) {
58
- this.contentWindow.postMessage(
59
- {
60
- jsonrpc: v,
61
- ...e
62
- },
63
- P
64
- );
103
+ /**
104
+ * Forward a JSON-RPC message to the content window.
105
+ */
106
+ forwardRpcResponseToIframe(e) {
107
+ P(this.iframeWidow, w.PROVIDER_RPC_RESPONSE, e);
65
108
  }
66
109
  }
67
- function y() {
110
+ function x() {
68
111
  return typeof window > "u" || !window ? "" : `https://swap-dev-git-${window.location.hostname.replace("widget-configurator-git-", "").replace("-cowswap.vercel.app", "")}-cowswap.vercel.app`;
69
112
  }
70
- const T = {
113
+ const k = {
71
114
  local: "http://localhost:3000",
72
115
  prod: "https://swap.cow.fi",
73
116
  dev: "https://dev.swap.cow.fi",
74
- pr: y()
75
- };
76
- var p = /* @__PURE__ */ ((n) => (n.SWAP = "swap", n.LIMIT = "limit", n.ADVANCED = "advanced", n))(p || {});
77
- const h = "_";
78
- function A(n) {
79
- const e = T[n.env || "prod"], t = f(n), o = w(n);
80
- return e + "/#" + t + "?" + o;
81
- }
82
- function f(n) {
83
- const { chainId: e = 1, sell: t, buy: o, tradeType: s = p.SWAP } = n, i = [(t == null ? void 0 : t.asset) || h, (o == null ? void 0 : o.asset) || h].map(encodeURIComponent).join("/");
84
- return `/${e}/widget/${s}/${i}`;
85
- }
86
- function w(n) {
87
- const { sell: e, buy: t, theme: o } = n, s = new URLSearchParams();
88
- return e != null && e.amount && s.append("sellAmount", e.amount), t != null && t.amount && s.append("buyAmount", t.amount), o && s.append("theme", typeof o == "string" ? o : o.baseTheme), s;
89
- }
90
- const c = "cowSwapWidget", m = "640px", C = "450px", M = 20;
91
- function S(n, e = {}) {
92
- const { provider: t } = e, o = _(e);
117
+ pr: x()
118
+ }, A = "_";
119
+ function Q(n) {
120
+ const e = k[n.env || "prod"], t = y(n), r = L(n);
121
+ return e + "/#" + t + "?" + r;
122
+ }
123
+ function y(n) {
124
+ const { chainId: e = 1, sell: t, buy: r, tradeType: s = S.SWAP } = n, c = [(t == null ? void 0 : t.asset) || A, (r == null ? void 0 : r.asset) || A].map(encodeURIComponent).join("/");
125
+ return `/${e}/widget/${s}/${c}`;
126
+ }
127
+ function L(n) {
128
+ const { sell: e, buy: t, theme: r } = n, s = new URLSearchParams();
129
+ return e != null && e.amount && s.append("sellAmount", e.amount), t != null && t.amount && s.append("buyAmount", t.amount), r && s.append("theme", typeof r == "string" ? r : r.baseTheme), s;
130
+ }
131
+ class K {
132
+ constructor() {
133
+ p(this, "subscriptions", {});
134
+ }
135
+ on(e) {
136
+ const { event: t, handler: r } = e;
137
+ this.subscriptions[t] || (this.subscriptions[t] = []), this.subscriptions[t].push(r);
138
+ }
139
+ off(e) {
140
+ const { event: t, handler: r } = e;
141
+ this.subscriptions[t] && (this.subscriptions[t] = this.subscriptions[t].filter((s) => s !== r));
142
+ }
143
+ emit(e, t) {
144
+ this.subscriptions[e] && this.subscriptions[e].forEach((r) => r(t));
145
+ }
146
+ }
147
+ let j = 1;
148
+ class J {
149
+ constructor(e, t = []) {
150
+ p(this, "eventEmitter", new K());
151
+ p(this, "listeners", []);
152
+ p(this, "widgetListener");
153
+ p(this, "instanceNumber", j++);
154
+ this.contentWindow = e, this.updateListeners(t), this.widgetListener = R(
155
+ this.contentWindow,
156
+ l.EMIT_COW_EVENT,
157
+ (r) => this.eventEmitter.emit(r.event, r.payload)
158
+ );
159
+ }
160
+ stopListeningIframe() {
161
+ O(this.contentWindow, this.widgetListener);
162
+ }
163
+ updateListeners(e) {
164
+ for (const t of this.listeners)
165
+ this.eventEmitter.off(t);
166
+ this.listeners = e || [];
167
+ for (const t of this.listeners)
168
+ this.eventEmitter.on(t);
169
+ }
170
+ }
171
+ const U = "640px", Y = "450px", z = 20;
172
+ function C(n, e) {
173
+ const { params: t, provider: r, listeners: s } = e;
174
+ let c = r;
175
+ const o = B(t);
93
176
  n.innerHTML = "", n.appendChild(o);
94
- const { contentWindow: s } = o;
95
- if (!s)
96
- throw new Error("Iframe does not contain a window!");
97
- return I(s, e.appCode), L(o, e.height), t && new R(s).onConnect(t), o.addEventListener("load", () => {
98
- u(e, s);
99
- }), (i) => u(i, s);
100
- }
101
- function _(n) {
102
- const { width: e = C, height: t = m } = n, o = document.createElement("iframe");
103
- return o.src = A(n), o.width = e, o.height = t, o.style.border = "0", o;
104
- }
105
- function u(n, e) {
106
- const t = f(n), o = w(n).toString();
107
- e.postMessage(
108
- {
109
- key: c,
110
- method: "update",
111
- urlParams: {
112
- pathname: t,
113
- search: o
114
- },
115
- appParams: {
116
- ...n,
117
- provider: void 0
118
- }
177
+ const { contentWindow: a } = o;
178
+ if (!a)
179
+ throw console.error("Iframe does not contain a window", o), new Error("Iframe does not contain a window!");
180
+ const E = [];
181
+ E.push(X(a, t.appCode)), E.push(Z(o, t.height));
182
+ const h = new J(window, s);
183
+ let d = I(a, null, c);
184
+ return o.addEventListener("load", () => D(a, t, c)), {
185
+ updateParams: (i) => D(a, i, c),
186
+ updateListeners: (i) => h.updateListeners(i),
187
+ updateProvider: (i) => {
188
+ c = i, d = I(a, d, i);
119
189
  },
120
- "*"
121
- );
190
+ destroy: () => {
191
+ h.stopListeningIframe(), E.forEach((i) => window.removeEventListener("message", i)), n.removeChild(o);
192
+ }
193
+ };
122
194
  }
123
- function I(n, e) {
124
- window.addEventListener("message", (t) => {
125
- t.data.key !== c || t.data.method !== "activate" || n.postMessage(
126
- {
127
- key: c,
128
- method: "metaData",
129
- metaData: e ? { appCode: e } : void 0
130
- },
131
- "*"
132
- );
195
+ function I(n, e, t) {
196
+ e && e.disconnect();
197
+ const r = e || new $(n);
198
+ return t && r.onConnect(t), r;
199
+ }
200
+ function B(n) {
201
+ const { width: e = Y, height: t = U } = n, r = document.createElement("iframe");
202
+ return r.src = Q(n), r.width = e, r.height = t, r.style.border = "0", r;
203
+ }
204
+ function D(n, e, t) {
205
+ const r = !!t, s = y(e), c = L(e).toString();
206
+ P(n, w.UPDATE_PARAMS, {
207
+ urlParams: {
208
+ pathname: s,
209
+ search: c
210
+ },
211
+ appParams: {
212
+ ...e
213
+ },
214
+ hasProvider: r
215
+ });
216
+ }
217
+ function X(n, e) {
218
+ const t = R(window, l.ACTIVATE, () => {
219
+ O(window, t), P(n, w.UPDATE_APP_DATA, {
220
+ metaData: e ? { appCode: e } : void 0
221
+ });
133
222
  });
223
+ return t;
134
224
  }
135
- function L(n, e = m) {
136
- window.addEventListener("message", (t) => {
137
- t.data.key !== c || t.data.method !== "iframeHeight" || (n.style.height = t.data.height ? `${t.data.height + M}px` : e);
225
+ function Z(n, e = U) {
226
+ return R(window, l.UPDATE_HEIGHT, (t) => {
227
+ n.style.height = t.height ? `${t.height + z}px` : e;
138
228
  });
139
229
  }
140
- function b({ params: n, provider: e }) {
141
- const t = a(), o = a(null), s = a(null);
142
- return d(() => {
143
- o.current && (e && t.current !== e && (s.current = null), s.current ? s.current(n) : s.current = S(o.current, n));
144
- }, [e, n]), d(() => {
145
- t.current = e;
146
- }, [e]), /* @__PURE__ */ E("div", { ref: o });
230
+ function re(n) {
231
+ const { params: e, provider: t, listeners: r } = n, [s, c] = b(null), o = m(null), a = m(t), E = m(r), h = m(null), d = m(null), i = F(
232
+ (u, f) => {
233
+ try {
234
+ console.log(`[WIDGET] ${u}`), f();
235
+ } catch (T) {
236
+ const _ = `Error ${u.toLowerCase()}`;
237
+ console.error(`[WIDGET] ${_}`, T), c({ message: _, error: T });
238
+ }
239
+ },
240
+ [c]
241
+ );
242
+ return g(() => {
243
+ if (!h.current || JSON.stringify(o.current) === JSON.stringify(e))
244
+ return;
245
+ const u = h.current, f = d.current;
246
+ o.current = e, f === null ? i("Creating a new widget", () => {
247
+ d.current = C(u, { params: e, provider: a.current, listeners: r }), E.current = r;
248
+ }) : i("Updating the widget", () => f.updateParams(e));
249
+ }, [e]), g(() => {
250
+ if (!d.current || a.current === t)
251
+ return;
252
+ a.current = t;
253
+ const u = h.current;
254
+ u && i("Updating the provider", () => {
255
+ var f;
256
+ (f = d.current) == null || f.destroy(), d.current = C(u, { params: e, provider: a.current, listeners: r });
257
+ });
258
+ }, [t]), g(() => {
259
+ if (!d.current || E.current === r)
260
+ return;
261
+ const u = d.current;
262
+ i("Updating the listeners", () => u.updateListeners(r));
263
+ }, [r]), s ? /* @__PURE__ */ H("div", { style: { color: "#ff3a3a" }, children: [
264
+ s.message,
265
+ s.error.message && /* @__PURE__ */ v("pre", { style: { whiteSpace: "pre-wrap", fontSize: "0.75em" }, children: s.error.message })
266
+ ] }) : /* @__PURE__ */ v("div", { ref: h });
147
267
  }
148
268
  export {
149
- T as COWSWAP_URLS,
150
- b as CowSwapWidget,
151
- p as TradeType,
152
- S as cowSwapWidget
269
+ k as COWSWAP_URLS,
270
+ re as CowSwapWidget,
271
+ S as TradeType,
272
+ l as WidgetMethodsEmit,
273
+ w as WidgetMethodsListen,
274
+ C as createCowSwapWidget,
275
+ R as listenToMessageFromWindow,
276
+ P as postMessageToWindow,
277
+ M as stopListeningToMessageFromWindow,
278
+ O as stopListeningWindowListener
153
279
  };
@@ -1,6 +1,2 @@
1
- import { CowSwapWidgetParams, EthereumProvider } from '@cowprotocol/widget-lib';
2
- export interface CowSwapWidgetProps {
3
- params: CowSwapWidgetParams;
4
- provider?: EthereumProvider;
5
- }
6
- export declare function CowSwapWidget({ params, provider }: CowSwapWidgetProps): import("react/jsx-runtime").JSX.Element;
1
+ import { CowSwapWidgetProps } from '@cowprotocol/widget-lib';
2
+ export declare function CowSwapWidget(props: CowSwapWidgetProps): import("react/jsx-runtime").JSX.Element;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cowprotocol/widget-react",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "type": "commonjs",
5
5
  "description": "CoW Swap Widget Library. Allows you to easily embed a CoW Swap widget on your React application.",
6
6
  "main": "index.js",